Skip to content

Fix TTL GROUP BY for columns with nested LowCardinality types - #119879

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-ttl-group-by-nested-lowcardinality
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-ttl-group-by-nested-lowcardinality

Conversation

@groeneai

@groeneai groeneai commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #54669
Related: #87336
Related: #92971
Related: #108550

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

Fix an exception (ILLEGAL_COLUMN: Expected ColumnLowCardinality) that made every TTL ... GROUP BY ... SET merge fail for a table with a column whose type has LowCardinality nested inside Tuple, Array or Map. In builds with assertions the same merge aborted on an assertion instead.

Description

TTL <expr> GROUP BY <keys> SET <assignments> fails on every merge of a table holding a column whose
type carries LowCardinality below the top level (Tuple(a LowCardinality(String), b UInt32),
Array(LowCardinality(String)), Map(LowCardinality(String), UInt32)) and that is neither a
GROUP BY key nor a SET target. No non-default setting is needed.

On official 26.4.5.143, OPTIMIZE TABLE ... FINAL on such a table returns
Code: 44. DB::Exception: Expected ColumnLowCardinality, got String: While executing TTL. on every
attempt, so the rollup never happens and background TTL merges of that table fail permanently. In
builds with assertions the same insert aborts on the chassert in IColumn::assertTypeEquality. An
otherwise identical table without LowCardinality merges fine. Found by the AST fuzzer,
STID: 2508-3698:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110098&sha=b478bb4e25a432b6ad4385d4b057d1c783cf560a&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Root cause: AggregateFunctionFactory::get resolves aggregates on argument types with
LowCardinality removed recursively (convertLowCardinalityTypesToNested), and the implicit any
that TTLAggregationAlgorithm gives every uncovered column has an identity expression that never
restores the wrappers. The restore step already in finalizeAggregates (added by #92971 for #87336)
tested only result_column_type->lowCardinality(), the outermost wrapper alone.

This generalises that step to "the declared type carries LowCardinality anywhere", reusing
recursiveLowCardinalityTypeConversion. It is a strict generalisation: the top-level case #92971
fixed takes the same call, and 03774_ttl_group_by_lowcardinality stays green. The two guards leave
explicitly-SET parts and every non-LowCardinality type difference exactly as today. Independent
of #108550 and #119863.

Validation: the new test aborts on master, passes with the fix, 50/50 under randomised settings; the
local stateless ttl sweep is otherwise unchanged.


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

A `TTL <expr> GROUP BY <keys> SET <assignments>` merge failed for every table
holding a column whose type carries LowCardinality below the top level, such as
Tuple(a LowCardinality(String), b UInt32), Array(LowCardinality(String)) or
Map(LowCardinality(String), UInt32), when that column is neither a GROUP BY key
nor a SET target. On official 26.4.5.143, OPTIMIZE TABLE ... FINAL returned
`Code: 44 ... Expected ColumnLowCardinality, got String: While executing TTL.`
on every attempt, so the rollup never happened and background TTL merges of such
a table failed permanently. In builds with assertions the same insert aborted on
the chassert in IColumn::assertTypeEquality instead. No non-default setting is
needed to reach it, and removing LowCardinality from an otherwise identical
table makes the merge succeed.

AggregateFunctionFactory::get resolves every aggregate on
convertLowCardinalityTypesToNested(argument_types), i.e. recursiveRemoveLowCardinality
per argument, so an aggregate's result type has LowCardinality stripped at every
depth rather than only outermost. TTLAggregationAlgorithm gives each column that
is neither a GROUP BY key nor a SET target an implicit any() whose set part is an
identity expression over that stripped type, and finalizeAggregates appends the
result into result_columns, which is header.cloneEmptyColumns() and therefore
still carries the declared type. The restore step already in that loop tested
only result_column_type->lowCardinality(), the outermost wrapper, so a column
with LowCardinality nested inside Tuple, Array or Map was appended unconverted:
the destination element column is a ColumnLowCardinality and the source element
is the full column.

Generalise that test to "the declared type carries LowCardinality anywhere" and
convert from the produced type with recursiveLowCardinalityTypeConversion, which
already recurses through Nullable, Const, Array, Tuple and Map. This is a strict
generalisation, so the top-level case keeps taking the same call.

Both guards are load-bearing. The first leaves explicitly-SET parts untouched,
since TTLDescription wraps their expressions in _CAST and they already produce
the declared type. The second converts only when removing LowCardinality from
the declared type yields exactly the produced type, so every other type
difference is left as it is today and the change cannot turn a working merge
into a TYPE_MISMATCH; it also keeps the conversion within the shapes both
helpers agree on, so it cannot throw.

Explicitly-SET columns, GROUP BY key columns and the path that copies rows whose
TTL has not expired were each checked to be unaffected, before and after the
change.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 14, 2026
@groeneai

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

An independent model reviewed this before publication (engine: codex): 0 findings. My own cold
pass, taken before reading the implementer's evidence, found 4 nits and no blocker or major:

# Sev Finding Verdict Evidence / action
1 💡 no provenance for the defect actually fixed, only prior art for the top-level variant AGREE, fixed pre-publication added the AST fuzzer report for STID: 2508-3698, and Related: #54669, a user report of the same ILLEGAL_COLUMN
2 💡 "all 107 stateless ttl tests are green" overstated the sweep AGREE, fixed pre-publication 106 green; 00933_ttl_replicated_zookeeper fails identically without this change and never constructs TTLAggregationAlgorithm
3 💡 any() written with parentheses, against the in-tree rule for naming a function AGREE, fixed pre-publication reads any now
4 💡 LowCardinality(Nullable(T)) and two-level nesting are not committed test arms noted, not blocking both shapes were run and value-checked; they reach the same Array/Tuple/Map recursion with no additional branch. The three committed arms are the ones that each fail on their own without the fix

Sibling carriers checked and left unchanged: GROUP BY key columns keep their declared type because
Aggregator::Params::getHeader inserts header.getByName(key).cloneEmpty(); explicitly-SET parts
already produce it through the _CAST that TTLDescription adds; and TTLColumnAlgorithm's default
expression is wrapped by that same conversion.

I did not modify the code during review.

Session id: cron:clickhouse-review-slot-8:20260914-014700

@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0199ffe]

Summary: ❌

job_name test_name status info comment
BuzzHouse (amd_debug) FAIL
Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa) FAIL cidb

AI Review

Summary

This PR generalizes the existing TTLAggregationAlgorithm LowCardinality restoration so implicitly aggregated TTL ... GROUP BY ... SET columns with nested LowCardinality wrappers are converted back to the table-declared type before they are appended to the merged result block. I reviewed the current diff, the surrounding TTL aggregation and LowCardinality conversion paths, the regression test, and the prior PR discussion, and I did not find a correctness, safety, performance, or metadata issue that warrants an inline review comment.

Final Verdict

✅ No review findings.

LLVM Coverage Report

Measured on commit 0199ffe.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.40% -0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). labels Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0199ffe61 with master 7df5d31fe (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0199ffe

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. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
BuzzHouse (amd_debug) / Logical error: 'Inconsistent AST formatting: the original AST: (STID 1941-1bfa) format-then-reparse fidelity abort on a select list of the shape SELECT map(), toDecimal32('837775.0') (zero-argument map() beside a quoted numeric literal), aborting at src/Interpreters/executeQuery.cpp:2499. Not caused by this diff: the change is TTL GROUP BY output-type coercion in TTLAggregationAlgorithm.cpp plus one stateless test, so it touches no parser, no formatter and no AST node, and the failing tree contains no TTL node. Cross-PR signature: 290 rows / 180 distinct pull requests / 7 master rows over 30 days a fix task is created (investigating at full effort, fixing PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

How this head was measured:

  • CI is fully finished. Check-runs deduped by name to the newest attempt: 172 runs, incomplete = 0, 171 success or skipped, 1 failure, Finish Workflow = success at 06:30:12Z, well past the 20 minute ingestion buffer.
  • CIDB agrees exactly: one FAIL row for this head, the BuzzHouse (amd_debug) row above.
  • The open family PR Fix Inconsistent AST formatting for APPLY with a matcher-valued lambda body #114205 was deliberately NOT linked as the owner here. It fixes a different sub-shape (a matcher-valued lambda body under APPLY), so linking it would assert a fix that does not address this tree. Every other PR in this family is already merged and therefore already present on this branch, which is why a fix task rather than a link owns the row.

Session id: cron:our-pr-ci-monitor:20260914-133210

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the BuzzHouse (amd_debug) Inconsistent AST formatting red on head 0199ffe61fe62ba19ccb3c42c9335eab0a34b431: #120096

jh0x pushed a commit to jh0x/ClickHouse that referenced this pull request Sep 15, 2026
On the right-hand side of a comparison the parser reads SOME as the
array-quantifier keyword. That lookahead
(ParserExpressionImpl::tryParseOperand) requires exactly one expression
before the closing parenthesis, so SOME(a, b -> 1) fails it, rewinds, and
the tokens are re-read as an ordinary function call named SOME whose
argument list folds a, b -> body into a single lambda.

ASTFunction::formatImpl printed that name through backQuoteIfNeed, which
force-quotes a curated list of keyword-valued identifiers in
writeProbablyQuotedStringImpl. The list existed for exactly this problem
and already carried the quantifier twin ALL, but not SOME, so the name was
emitted bare. Re-parsing the emitted text, the bare SOME matched the
keyword again, and the content was now a single expression because the
formatter had parenthesised the lambda parameter list, so the quantifier
path fired and rewrote the node to arrayExists. The trees no longer
matched, and on a build with assertions the format-and-re-parse
consistency check in executeQuery.cpp raised LOGICAL_ERROR.

Two more spellings reach the same abort. The parser drops the ALL aggregate
qualifier, so SOME(ALL 2) also collapses to one expression on the way back.
And the quantifier has a second branch: a subquery argument, which is
rewritten to IN rather than to arrayExists, so `SOME`((SELECT 1)) breaks
too. Quoting the name fixes all three at once, because it acts before the
parser chooses a branch.

ANY is deliberately left out of the list. A function named ANY with a
non-subquery argument round-trips unchanged, but the back-quoted subquery
spelling `ANY`((SELECT 1)) does not, on master as much as here: the name is
emitted bare and read back as the quantifier, so the node becomes IN.
Adding any to this list would fix that at the cost of back-quoting the any
aggregate function in every EXPLAIN SYNTAX and SHOW CREATE output, which is
a different change with a different blast radius, so this commit keeps to
the name CI produced.

Only formatter output changes. The parser has always accepted both
spellings, so metadata written by a new server is readable by an old one
and vice versa, and no setting or serialization surface is involved.

Found by BuzzHouse (`amd_debug`) on an unrelated pull request:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119879&sha=0199ffe61fe62ba19ccb3c42c9335eab0a34b431&name_0=PR&name_1=BuzzHouse%20%28amd_debug%29

Related: ClickHouse#119879

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

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-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant