Skip to content

Refuse a pure window function inside the AggregateFunction data type - #122148

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:refuse-window-function-state-column-type
Sep 26, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:refuse-window-function-state-column-type

Conversation

@groeneai

@groeneai groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121996

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A data type naming the state of a function that only works as a window function, such as AggregateFunction(rank), is now rejected with BAD_ARGUMENTS: such a state has no serialization, so the column could never hold a value. This applies wherever a type is named, including inside Array/Map/Tuple and another state's argument list. A table that already stores such a column will no longer attach.

Description

Follow-up to #121996, as asked there. The check is in the type's create().

On master CREATE TABLE t (c AggregateFunction(rank)) ENGINE = Memory succeeds and reopens, yet that column can never hold a value: every WindowFunction entry point calls fail(). The creator resolves the function and never asks whether it is a real aggregate function, though the predicate exists for exactly that (isOnlyWindowFunction(), already used at AggregateFunctionFactory.cpp:128).

One check there covers every declaration surface, including two a storage-level check cannot see (a full-definition ATTACH ... UUID, a table function's structure), and covers nesting for free: c Array(AggregateFunction(rank)) slipped through the storage-level version. 4 files, ~15 lines, no new setting. Full matrix below.

Two paths build the type through its constructor, not create(): a binary-encoded type decode, and a column type inferred from a query. So rankState(), or another window function's -State, in a view, CREATE TABLE ... [EMPTY] AS SELECT, or CREATE TABLE ... AS such a view or a column-less Merge over it, is still created but fails to attach after DETACH or a restart. The one undeclared surface that changes is the wire: an empty result whose Native header names the type is now refused by the receiver.

New test 05257_window_function_state_column_type_rejected: one line per surface, the SELECT spellings added on review, plus controls that an ordinary state still round-trips through DETACH/ATTACH, that sumMerge still reads a stored state in a CAST and in a table function, and that rank() OVER () still works. None of its 20 refusal lines is refused on master. 35/50 randomized runs pass, the 15 others on a timezone artifact that SELECT 1 reproduces here. The 381 window-function and aggregate-state stateless tests ran on this build and a master build with no attributable difference, and AggregateFunctionFactory.cpp:128 is unchanged on four -If probes.

Surface matrix, each with its site, measured against a master build
surface site result
CREATE, declared columns of CREATE AS SELECT InterpreterCreateQuery.cpp:643 rejected
ALTER ADD/MODIFY COLUMN AlterCommands.cpp:256/:326 rejected
full-definition ATTACH ... UUID same as CREATE rejected
table function structure parseColumnsListForTableFunction.cpp:180 rejected
CAST, castOrDefault, :: CastOverloadResolver.cpp:243 rejected
Array/Map/Tuple/Nullable, state-as-argument child DataTypeFactory calls rejected, no setting gates it
12 singular combinators, and -Tuple getNestedFunction() hop; AggregateFunctionTuple.cpp:603 rejected
SimpleAggregateFunction(rank) DataTypeCustomSimpleAggregateFunction.cpp:62 already refused, unchanged
stored metadata (ATTACH, restart) DatabaseOnDisk.cpp:148 rejected: an existing stored column stops attaching
column type inferred from a query: CREATE VIEW, CREATE TABLE ... [EMPTY] AS SELECT, AS <view>, column-less Merge getStateType(), the constructor still created; fails to attach after DETACH or a restart
binary-encoded type decode DataTypesBinaryEncoding.cpp:776, the constructor still decodes, unchanged
an empty result's type name over TCP NativeReader.cpp:80 receiver refuses
values(), schema-inference hints try-parse, parseColumnsListForTableFunction.cpp:187 throw swallowed: the structure is taken as data, as for any unknown type

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

Version info

  • Merged into: 26.10.1.731-master (included in 26.10 and later)

@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 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (6 rounds, 0 findings outstanding)

An independent model reviewed this change cold each round, then a second pass re-reviewed the result statefully. Gate findings went 2, 1, 2, 2, 1, 0; the last round is clean on both passes.

Fixed during review

  • ❌ The refusal threw from inside the recursive walk, so it named the node the walk stopped at and no column: a Map(String, AggregateFunction(rank)) column was reported as AggregateFunction(rank), a string absent from the user's DDL. It now names the declared type, the column and the function.
  • ❌ The message claimed the column "could never hold a value", false for a state an outer function discards: AggregateFunction(count, AggregateFunction(rank)) holds an ordinary counter (measured on the pre-fix binary: countMerge = 3, serialized state = the single byte 03). It now states the syntactic rule it implements, and one test statement pins the case so it cannot later be "corrected" as an over-rejection.
  • ❌ The post-construction check on engine-inferred schemas had no oracle: every negative case declared its type explicitly and was caught by the pre-construction validator instead, so deleting that call left the whole test file green. A view is the one carrier that reaches it; one assertion now covers it, and a mutant removing only that call reddens exactly that line.
  • ❌ Restore provenance reached neither internal re-creation of a stored definition: a materialized view's inner table (round 4) and a TimeSeries table's four inner tables (round 5) are each re-created by a nested InterpreterCreateQuery that ran as a fresh definition, so restoring a backup predating this check failed with ILLEGAL_COLUMN. Both now carry the flag, measured cross-binary in both directions because no binary carrying the check can build the fixture.
  • ⚠️ The replay test arm attached an ordinary state, so it could not demonstrate the compatibility promise its section implied; its comment now claims only what it proves, and the stored-state direction rests on the cross-binary probes, since no API surface can produce such a state once the check exists.

Declined, with evidence

  • 💡 A refreshable view's Replace refresh re-executes its target's stored definition as a fresh CREATE OR REPLACE, so a grandfathered target column is refused there; this is disclosed in the changelog. It is not a regression for any spelling whose state is genuinely unserializable, because those refreshes already failed before this PR at execution time (REFRESH_FAILED wrapping "can only be used as a window function" from AggregatingTransform, measured); only the discarded-argument spelling regresses, and ALTER TABLE <inner> MODIFY COLUMN is measured to restore refreshing. Exempting the clone means flipping a marker four unrelated validators read, which is a separate design change.
  • 💡 ILLEGAL_COLUMN rather than DATA_TYPE_CANNOT_BE_USED_IN_TABLES: both are already idiomatic at this seam (the same function throws ILLEGAL_COLUMN twice), the message carries the diagnostic load, and the test asserts the symbolic name.
  • 💡 No CREATE TEMPORARY TABLE assertion in the shipping test, though temporary tables are deliberately screened: it shares its seam with the plain CREATE arms that are asserted, and the shape was measured during implementation.

Checked independently and found sound

The predicate forwards through getNestedFunction(), matching the three sibling predicates in the same class; -Tuple is the only combinator without that override, which is why it needs the hand-override. Its only pre-existing consultation is the implicit Null nullability adapter, and five negative controls are byte-identical across binaries, so no working query changes. Coverage is closed-form rather than a name list: the four paths from a declared column type to an aggregate function are the declared type, a forEachChild descendant, another state's argument types, and a combinator's nested function, and three mutants redden them independently. SimpleAggregateFunction needs no change, its own allow-list already refuses these names. validateDataType and CAST are deliberately untouched: a stored SELECT is re-analysed on ATTACH, so refusing there would break the load this change keeps working. AlterCommands::validate has a single caller, so a replica applying metadata from Keeper never reaches the ALTER gate. Of the nine nested InterpreterCreateQuery sites in src/, every one except the refresh clone above is exempt. Cost is DDL-only: one typeid_cast per declared column and one extra virtual call where a combinator wrapper is present, on no query path.

@groeneai

groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, one command, no randomization: clickhouse local --path=$D -q "CREATE TABLE t (c AggregateFunction(rank)) ENGINE = Memory". Master accepts it (rc=0); this build refuses it with Code: 36.
b Root cause explained? DataTypeAggregateFunction's factory creator resolves the named function and builds the type without asking whether it is a real aggregate function, so a WindowFunction subclass becomes the type's function and every surface that turns a type name into a type accepts a state that has no serialization (WindowFunction.h:75-86 calls fail() from add, mergeImpl, serialize, deserialize, insertResultInto).
c Fix matches root cause? Yes: the screen goes at the creator, using the in-tree predicate that already carries this meaning (isOnlyWindowFunction(), WindowFunction.h:73, consulted at AggregateFunctionFactory.cpp:128). No widened bound, no no-random-* tag, no reduced dataset, no new setting, no guard at a failure site.
d Test intent preserved / new tests added? No existing test modified. One new stateless test, 05257_window_function_state_column_type_rejected: one line per distinct surface plus three positive controls (an ordinary state still round-trips through DETACH/ATTACH, sumMerge still reads a stored state, rank() OVER () still works as a window function).
e Both directions demonstrated? Yes, twice. 11 refusal surfaces measured against a master build: 8 accepted there, 2 gave a different code (Code: 70), all 11 now Code: 36. And with only the create() hunk reverted, each of the 10 lines the test asserts as BAD_ARGUMENTS returns something else (8 accepted, 2 Code: 70), so no assertion is vacuous; the file itself then fails 3/3 through the runner.
f Fix is general across code paths? This is the point of the site: one check in the single place where a written AggregateFunction(...) becomes a type, so CREATE, ALTER, full-definition ATTACH, CAST and a table function's structure are all covered by it. The sibling creator already refuses this way and needed no edit (DataTypeCustomSimpleAggregateFunction.cpp:62, called from its create() at :156), measured still refusing. The only pre-existing consumer of the predicate, AggregateFunctionFactory.cpp:128, is byte-identical on four -If probes.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured: Array wrapper; a state as another state's argument; the -State, -OrNull and -Tuple combinators; zero-arg and parameterised spellings (rankTuple, Tuple(UInt64) under allow_rank_dense_rank_arguments = 1); a table function's structure; CAST; ATTACH ... UUID; ALTER ADD and ALTER MODIFY. rankArray and rankNull are not constructible at all (TOO_FEW_ARGUMENTS_FOR_FUNCTION; the Null combinator is internal-only), so there is nothing to assert for them.
h Backward compatible? (maintainer-approved exception only) Deliberately not, and that is the changelog category: it rejects a CREATE master accepts, and an existing stored column stops attaching. @ PedroTadim chose this site in writing on #122148 after the attach cost was stated to him. No setting is added or changed, so no SettingsChangesHistory.cpp entry; no serialization format change and no version gate.
i Invariants and contracts preserved? create() throws before constructing the type, so no partially built DataTypeAggregateFunction exists on the error path. The added predicate bodies are const, allocation-free and have no early-return path; AggregateFunctionTuple's any_of fold matches its two sibling predicates immediately above it. The load and restart re-entry path is the accepted break, measured across binaries rather than assumed.

Session id: cron:clickhouse-impl-slot-7:20260925-091300

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f3ff7c8]

Summary: ✅


AI Review

Summary

This PR adds the right check for explicitly named AggregateFunction(window_fn, ...) types and threads isOnlyWindowFunction() through combinators, so the direct CREATE / ALTER / CAST / table-function structure surfaces look covered. I still see one remaining inferred-schema path that can mint the forbidden state type without going through the new guard, so I would not merge this as-is.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Refuse a pure window function inside the AggregateFunction data type #122148#issuecomment-5831185946] [src/DataTypes/DataTypeAggregateFunction.cpp:343-348, src/AggregateFunctions/IAggregateFunction.cpp:15-18, src/Interpreters/InterpreterCreateQuery.cpp:1153-1169] The new check only runs when a spelled AggregateFunction(...) name is parsed. Inferred-schema paths still obtain state types directly from IAggregateFunction::getStateType(), which constructs DataTypeAggregateFunction without re-running this validation. A zero-result-group CREATE TABLE ... AS SELECT rankState() ... path can therefore still persist an AggregateFunction(rank) column, and that fresh metadata then fails on a later ATTACH or restart. I still consider this real because the PR promises to refuse these states in the data type, but this path still creates a stored schema that the same build later cannot load. Suggested fix: enforce the same rule at the common constructor-based minting boundary, or reject such inferred output types before persisting columns_from_select.
Tests
  • The new stateless test covers explicit declarations, combinator spellings, CAST, and table-function structure, but it does not cover the constructor-based inferred-schema path above. A regression test needs a zero-result-group schema-inference case, such as CREATE TABLE ... AS SELECT rankState() ..., or another sample-block carrier that proves fresh metadata can no longer store the forbidden state type.
Final Verdict

Changes requested: explicit type parsing is fixed, but inferred-schema creation can still materialize a fresh AggregateFunction(rank) column that the same build later refuses to attach.

LLVM Coverage Report

Measured on commit f3ff7c8.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). labels Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f3ff7c84b with master ef8d752e5 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 313e6e829; 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

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

Median compile-time ratio to the baselines is ×1.07 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +179.8 s (+8%) in total before that adjustment.

Job report

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai this seems to be another complete slop! What I said is to disallow window functions inside the AggregateFunction data type. Can that be done in the type's validator? You don't have to mess up CREATE statements. I think this PR may have to be scrapped altogether

@PedroTadim PedroTadim self-assigned this Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, and doing it there removes the CREATE plumbing you are objecting to.

validateDataType() (src/Interpreters/parseColumnsListForTableFunction.cpp:50) is the validator every declared column already passes: CREATE and CREATE ... AS (InterpreterCreateQuery.cpp:1253), ALTER ADD/MODIFY COLUMN (AlterCommands.cpp:2191,2289), CAST (CastOverloadResolver.cpp:244), a table function's structure argument. It is where allow_suspicious_low_cardinality_types and friends reject a type, and it is already skipped for ATTACH and for views (InterpreterCreateQuery.cpp:1248). One isOnlyWindowFunction() check there, and InterpreterCreateQuery, AlterCommands, StorageFactory, the two replay predicates and the StorageMaterializedView/StorageTimeSeries threading all come out of this PR. It leaves two holes that every other check in that function also has: a full-definition ATTACH TABLE ... UUID ... (...), and a column an engine infers after construction.

What that site cannot do is refuse the type on the load path. For that the site is DataTypeAggregateFunction's own create() (DataTypeAggregateFunction.cpp:272), where SimpleAggregateFunction keeps its allow-list (DataTypeCustomSimpleAggregateFunction.cpp:60). A check there fires everywhere, including when an existing AggregateFunction(rank) column is read back from metadata, so a table that has one stops attaching. On master such a column creates and reloads today, and it can never hold a value (WindowFunction::serialize throws), so that table is always empty.

I am replacing this PR's diff with the validateDataType version rather than opening a third PR, and the test shrinks with it. Tell me if you would rather have it in the type's create() and take the attach break.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai I want in the the type's create(). Also, don't forget to validate with table functions. Those should be rejected too.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood: the refusal goes into DataTypeAggregateFunction::create(), and I take the attach break as your call (no setting, no softening).

Table functions are covered by that same site. A structure argument goes through parseColumnsListFromString -> InterpreterCreateQuery::getColumnsDescription -> DataTypeFactory::get, which is the same creator, so DESCRIBE TABLE format(JSONEachRow, 'c AggregateFunction(rank)', ''), accepted on master 26.10.1.1 today, is rejected as well. It gets its own test arm.

So I am rewriting this PR's diff on the same branch: one check in the type creator instead of the CREATE/ALTER/storage plumbing, 15 files down to 4, and the test shrinks with it. I will post here when it is pushed.

DataTypeAggregateFunction's factory creator resolved the named aggregate
function and built the type without asking whether that function is a real
aggregate function, so a WindowFunction subclass could become the type's
function. Such a state has no serialization: WindowFunction::add, mergeImpl,
serialize, deserialize and insertResultInto all call fail(). The column was
therefore accepted everywhere a type name is parsed, and could never hold a
value.

Screen it at the creator with isOnlyWindowFunction(), which already carries
exactly this meaning and is already consulted at AggregateFunctionFactory.cpp
under the comment "Pure window functions are not real aggregate functions".
That is one check at the single place a written AggregateFunction(...) becomes
a type, so CREATE, ALTER, a full-definition ATTACH, CAST and a table
function's structure argument are all covered by it, and nesting is covered
for free because Array/Map/Tuple creators and the state's own argument list
build their children through DataTypeFactory. The storage-level alternative
missed the full-definition ATTACH, missed a table function's structure, and
let Array(AggregateFunction(rank)) through.

Two supporting hunks make the predicate answer for combinators. The base
implementation now forwards one getNestedFunction() hop, which is what 12
singular combinators need, since they override getNestedFunction() and not
isOnlyWindowFunction(). AggregateFunctionTuple has no single nested function
to forward to, so it folds over nested_functions with any_of, matching the two
sibling predicates beside it.

BAD_ARGUMENTS rather than ILLEGAL_COLUMN, because this creator also runs for a
CAST and for a table function's structure, where there is no column; the same
code is what this creator already throws for a malformed function name, what
the sibling SimpleAggregateFunction creator throws to refuse an unsupported
function, and what WindowFunction::fail() throws for this same rule at
runtime.

This is a backward incompatible change, not a bug fix: no released version
returns a wrong answer, loses data or rejects a valid input here. It removes
an input that was accepted, and a table that already stores such a column
stops attaching, because the refusal also fires when stored metadata is
re-parsed. That cost was stated before the site was chosen.

Deliberately out of scope, all three because they do not go through create():
rankState() with zero result groups still mints the type via getStateType(),
so such a table will not reattach; the same type name in an empty result's
Native header is refused by the receiver; and a view stores its query rather
than column types. Gating the constructor would move rankState()'s failure
from execution to analysis.

Related: ClickHouse#121996
@groeneai
groeneai force-pushed the refuse-window-function-state-column-type branch from 443f49e to 35257b7 Compare September 25, 2026 10:50
@groeneai groeneai changed the title Refuse a window function state as a column type where the user declares it Refuse a pure window function inside the AggregateFunction data type Sep 25, 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; 1 finding) plus my own cold read of
the diff, which raised 3 more. The diff is unchanged by this round: the 3 were in the PR body and I
corrected them there.

# Sev Finding Verdict Evidence / action
1 ❌ CREATE TABLE ... AS SELECT rankState() ... GROUP BY with zero result groups still mints an AggregateFunction(rank) column, through the constructor rather than create(), and that table then will not reattach. Remedy asked for: enforce the rule at fresh storage-schema validation or another common boundary, plus a regression test DISAGREE The mechanism is real, measured, and disclosed in the body with its site: CTAS returns rc=0 on both a master build and this one, and ATTACH then returns rc=0 on master and Code: 36 here. What I disagree with is that this PR should close it. Storage-schema validation is the site scrapped in this thread on 25 Sep 07:23Z; the only other common boundary is the type's constructor, and AggregateFunctionState's constructor calls nested_->getStateType() in its initializer list (AggregateFunctionState.h:36-38), so a screen there fires inside AggregateFunctionFactory::get and rankState stops resolving at all, which is a function-resolution rule rather than a data-type one. The harm ceiling is an empty table: no WindowFunction subclass overrides serialize, so fail() is the only implementation and count() is 0. That is the load-path cost priced on this thread at 08:10Z and chosen at 08:12Z, reached by a different mint path. The changelog scopes the refusal to wherever a type is named, and a CTAS names none. Left as a disclosed limitation rather than a promise, for you to rule on
2 ⚠️ The provenance link was wrapped in an HTML comment, so it would not have rendered AGREE, fixed Visible Related: line restored at the top of the body
3 💡 The surface matrix omitted the binary-encoded type decode, which also builds the type through the constructor AGREE, fixed One matrix row added, DataTypesBinaryEncoding.cpp:776, unchanged by this PR
4 💡 The body said three surfaces are untouched "because they do not go through create()", then listed the Native header, where the receiver refuses precisely because it does go through create() AGREE, fixed Reworded: the three constructor mint paths are named as such, and the wire is stated separately as the one surface that changes without being declared anywhere

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

Session id: cron:clickhouse-review-slot-48:20260925-100600

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed the create() version onto this branch. DataTypeAggregateFunction's creator now asks isOnlyWindowFunction() right after it resolves the function and throws BAD_ARGUMENTS, so the CREATE plumbing you objected to is gone: 4 source files, no new setting.

Table functions are covered by that same site, because a structure string reaches the same creator; the test pins it with format('CSV', 'c AggregateFunction(rank)', ''), alongside Array, a state inside another state's argument list, the -State and -Tuple combinators, a full-definition ATTACH ... UUID, CAST, ALTER ADD and ALTER MODIFY, in one file. The attach break is taken as your call and is in the changelog: a table that already stores such a column stops attaching.

One shape that site does not reach, stated in the body with its line: rankState() over zero result groups mints the type through the constructor, so CREATE ... AS SELECT can still leave a table that will not reattach. Screening the constructor instead would stop rankState resolving anywhere, a wider rule than this one, so I left it.

DROP TABLE IF EXISTS t_window_state;
DROP TABLE IF EXISTS t_window_state_ok;

CREATE TABLE t_window_state (c AggregateFunction(rank)) ENGINE = Memory; -- { serverError BAD_ARGUMENTS }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai I want to see more SELECT test cases

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in f3ff7c8, grouped by what each arm exercises:

  • spellings: CAST(NULL, '...'), CAST(NULL AS ...), NULL::..., and a Tuple(...) wrapper;
  • the function's own shape: no argument (row_number), an argument (lagInFrame), a parameter (exponentialTimeDecayedSum(1)), a combinator (rankIf);
  • a table function's structure, read as rows (format, null, generateRandom) and through DESCRIBE file(...);
  • controls: an ordinary aggregate state still CASTs in a SELECT and still resolves as a structure, and rank() OVER () still works.

None of the 12 new refusal lines is refused on master: the CAST spellings got as far as converting the value (CANNOT_CONVERT_TYPE), null(...) and DESCRIBE file(...) returned AggregateFunction(rank) as a column type, and generateRandom refused it for its own reason.

One table function does not reject, and that call is yours rather than mine: values('c AggregateFunction(rank)', (NULL)) returns a String column. values() decides structure-or-data by trying to parse its first argument, and any parse failure makes it data, so the refusal is swallowed. It is not specific to this type: values('c NoSuchType', (NULL)) and values('hello world', 'foo bar') behave the same way on master, and making that try-parse propagate would make both of those throw and would change schema_inference_hints with them. The test records the current result on one line; tell me to reject it and I will.

SELECT rankState() over zero result groups still mints the type through the constructor rather than the creator, as the description says.

@clickhouse-gh clickhouse-gh Bot added comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). and removed comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). labels Sep 25, 2026
Requested on the test file: more SELECT test cases.

The type creator runs for every statement that names the type, so the SELECT
side has more spellings than the DDL side has: CAST in all three spellings, a
wrapper around it, a function that takes an argument or a parameter, a
combinator, and a table function's structure argument read either as rows or
through DESCRIBE. Each added arm reaches the creator by a different route, and
none of them is refused on master: CAST and its wrappers got as far as
converting the value, null() and DESCRIBE over file() returned the state type,
and generateRandom() refused it for its own reason.

values() is the one spelling where nothing is created: it resolves a first
argument that does not parse as a structure as data instead, which it already
does for an unknown type name, so the arm records the String column it returns.

The added positive controls keep an ordinary aggregate state working in the
same two places: a CAST in a SELECT, and a table function's structure.
@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into ClickHouse:master with commit 0995a51 Sep 26, 2026
176 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — title/description suggestions:

Description (currently misleading):

  • Why: The body leaves views alone because a view "stores its query rather than column types". View metadata stores the column list (SHOW CREATE VIEW prints s AggregateFunction(rank)), so such a view is created and then fails ATTACH on this build.

  • Suggested addition:

    A view whose SELECT yields a window-function -State column (for example rankState() OVER (...)) is still created, but its stored column list names the type, so it no longer re-attaches after DETACH or a restart. The same holds for CREATE TABLE ... AS <view> and a column-less Merge over it.

Ignore if intentional.

pull Bot pushed a commit to Dream-hu/ClickHouse that referenced this pull request Sep 30, 2026
…ader builds it

ClickHouse#122148 refused `AggregateFunction(<window-only function>)` in the type's
`create`, which parses a type name. The same type is also built by the
constructor of the `-State` combinator (`rankState`, `denseRankStateIf`,
`lagInFrameState`, `initializeAggregation('lagInFrameState', x)`, ...) and by
the binary type decoder (a `Native` header read with
`input_format_native_decode_types_in_binary_format = 1`). A view, a
`CREATE TABLE ... AS SELECT` or a `CREATE TABLE ... AS format(Native, ...)`
then stored `AggregateFunction(rank)` in its metadata, and every later load
parsed that name through `create` and failed: `ATTACH` failed with `Code: 36`,
after a restart `system.tables` failed server-wide with `Code: 722`, and with
`async_load_databases = 0` the server did not start.

The check moves into `DataTypeAggregateFunction::checkSupportedFunctions` and
runs at the three places where a caller-chosen function becomes this type:
`create`, `AggregateFunctionState`'s result type (the combinator and the
`Null` adapter both construct that class) and the `AggregateFunction` case of
the binary type decoder. This mirrors `SimpleAggregateFunction`, whose
`checkSupportedFunctions` already runs both in its `create` and in the
`-SimpleState` result type, which is why `rankSimpleState` was already refused
when the query is analyzed.

A window-only function's `-State` already failed on its first row, as an
aggregate and inside `OVER`, so the error now comes at analysis instead.

Reported by an automated review of ClickHouse#122148:
ClickHouse#122148 (comment)

Co-Authored-By: Claude Opus 5.5 <[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 comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backward-incompatible Pull request with backwards incompatible changes pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants