Repository navigation
Refuse a pure window function inside the AggregateFunction data type - #122148
alexey-milovidov merged 2 commits into
Conversation
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
Declined, with evidence
Checked independently and found sound The predicate forwards through |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260925-091300 |
|
Workflow [PR], commit [f3ff7c8] Summary: ✅
AI ReviewSummaryThis PR adds the right check for explicitly named Findings
Tests
Final VerdictChanges requested: explicit type parsing is fixed, but inferred-schema creation can still materialize a fresh LLVM Coverage ReportMeasured on commit f3ff7c8.
Changed lines: Changed C/C++ lines covered: 12/12 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units315 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. |
|
@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 |
|
Yes, and doing it there removes the CREATE plumbing you are objecting to.
What that site cannot do is refuse the type on the load path. For that the site is I am replacing this PR's diff with the |
|
@groeneai I want in the the type's create(). Also, don't forget to validate with table functions. Those should be rejected too. |
|
Understood: the refusal goes into Table functions are covered by that same site. A 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
443f49e to
35257b7
Compare
AggregateFunction data type
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
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-48:20260925-100600 |
|
Pushed the Table functions are covered by that same site, because a One shape that site does not reach, stated in the body with its line: |
| 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 } |
There was a problem hiding this comment.
Added in f3ff7c8, grouped by what each arm exercises:
- spellings:
CAST(NULL, '...'),CAST(NULL AS ...),NULL::..., and aTuple(...)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 throughDESCRIBE file(...); - controls: an ordinary aggregate state still
CASTs in a SELECT and still resolves as a structure, andrank() 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.
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.
|
@groeneai @alexey-milovidov — title/description suggestions: Description (currently
Ignore if intentional. |
…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]>
Related: #121996
Changelog category (leave one):
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 withBAD_ARGUMENTS: such a state has no serialization, so the column could never hold a value. This applies wherever a type is named, including insideArray/Map/Tupleand 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 = Memorysucceeds and reopens, yet that column can never hold a value: everyWindowFunctionentry point callsfail(). 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 atAggregateFunctionFactory.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'sstructure), 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. SorankState(), or another window function's-State, in a view,CREATE TABLE ... [EMPTY] AS SELECT, orCREATE TABLE ... ASsuch a view or a column-lessMergeover it, is still created but fails to attach afterDETACHor 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 throughDETACH/ATTACH, thatsumMergestill reads a stored state in aCASTand in a table function, and thatrank() 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 thatSELECT 1reproduces here. The 381 window-function and aggregate-state stateless tests ran on this build and a master build with no attributable difference, andAggregateFunctionFactory.cpp:128is unchanged on four-Ifprobes.Surface matrix, each with its site, measured against a master build
CREATE, declared columns ofCREATE AS SELECTInterpreterCreateQuery.cpp:643ALTER ADD/MODIFY COLUMNAlterCommands.cpp:256/:326ATTACH ... UUIDCREATEstructureparseColumnsListForTableFunction.cpp:180CAST,castOrDefault,::CastOverloadResolver.cpp:243Array/Map/Tuple/Nullable, state-as-argumentDataTypeFactorycalls-TuplegetNestedFunction()hop;AggregateFunctionTuple.cpp:603SimpleAggregateFunction(rank)DataTypeCustomSimpleAggregateFunction.cpp:62ATTACH, restart)DatabaseOnDisk.cpp:148CREATE VIEW,CREATE TABLE ... [EMPTY] AS SELECT,AS <view>, column-lessMergegetStateType(), the constructorDETACHor a restartDataTypesBinaryEncoding.cpp:776, the constructorNativeReader.cpp:80values(), schema-inference hintsparseColumnsListForTableFunction.cpp:187Workflow [PR]
Sync PR [sync-upstream/pr/122148]
Version info
26.10.1.731-master(included in26.10and later)