Skip to content

Reject window PARTITION BY and ORDER BY over an aggregate function state - #113878

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:deprecate-window-partition-by-aggregate-state
Aug 15, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:deprecate-window-partition-by-aggregate-state

Conversation

@groeneai

@groeneai groeneai commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Backward Incompatible Change

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

A window PARTITION BY or ORDER BY over an AggregateFunction column is now rejected with ILLEGAL_COLUMN, as top-level ORDER BY over such a column already was. Previously such a query was accepted by at least one analyzer, and window PARTITION BY partitioned differently depending on max_threads. The refusal also covers a state nested in Array, Tuple, Map, Variant or SimpleAggregateFunction. A SimpleAggregateFunction over an ordinary type, QBit, and GROUP BY and DISTINCT over a state, are unaffected.

Description

The two partitioning paths react differently to a state: the sort path calls ColumnAggregateFunction::compareAt, a stub returning 0 unconditionally, so all states collapse into one partition, while the scatter path hashes their raw bytes and scatters them. On the reporter's fixture dense_rank() gives 1,1,2,3,4,5,6,7,8 at max_threads = 1 and 1,1,2,3,1,4,2,5,6 at max_threads = 8.

Validation missed it because window PARTITION BY routes through validateGroupByKeyType, which rejects only Dynamic and Variant, not through validateSortingKeyType, which carries the comparability check. The old analyzer's window ORDER BY branch validated no sort-key types at all, so rank() OVER (ORDER BY st) over nine distinct states returned nine 1s there while the analyzer refused it. Both clauses are now guarded in both analyzers; guarding one leaves the other wrong.

The predicate is the existing hasAggregateFunctionType rather than a comparability predicate, which would also reject QBit; control rows pin that for both clauses. It follows a SimpleAggregateFunction to its storage type, so SimpleAggregateFunction(sum, UInt64) stays accepted while SimpleAggregateFunction(any, AggregateFunction(uniq, UInt64)) is refused. GROUP BY and DISTINCT over a state are stable and untouched, so the shared helper is unchanged. No SettingsChangesHistory.cpp entry is owed, as in PR 105450.

Validated on debug builds with each server's buildId asserted before any verdict: the test fails on the parent and passes here, 50 randomized and 50 plain runs pass, each mutant is caught only by the rows meant to catch it, and a 162-test window slice has the same deterministic failures on both binaries.

Compatibility note on projections

A projection whose SELECT contains OVER (PARTITION BY <state>) could be created before this change. A server restart still loads the table and all its rows, dropping the projection from system.projections so its parts stop being used. An explicit ATTACH TABLE of such a table instead fails with ILLEGAL_COLUMN and leaves it detached until the next restart. The merged Dynamic and Variant equivalent, PR 105450, behaves the same way on master today. No stateless test can pin this, because the fixed binary cannot create the projection the case starts from. The ORDER BY half adds nothing here: a projection sorting a window by a state is refused identically before and after.

One boundary left for you to rule on, also asked in the issue thread: a state reached through Dynamic shows the same instability but is not covered, Dynamic exposing no children; it needs allow_suspicious_types_in_group_by = 1, whose error text already warns about unexpected results. A state inside Variant is refused. Both pinned by the test.

A window PARTITION BY an AggregateFunction column was accepted and partitioned
differently depending on max_threads, while ORDER BY over the same column has
always been refused. Reported in ClickHouse#113247.

DataTypeAggregateFunction does not override IDataType::isComparable, which
defaults to false, and the two partitioning paths react differently to that:
the sort path calls ColumnAggregateFunction::compareAt, a stub returning 0
unconditionally, so every state compares equal and the whole input collapses
into a single partition; the scatter path hashes the key columns' raw bytes, so
semantically equal but byte-different states land in different partitions.
Which path runs depends on max_threads, so the same query answers differently
at different thread counts. On the reporter's fixture, dense_rank() returns
1,1,2,3,4,5,6,7,8 at max_threads = 1 and 1,1,2,3,1,4,2,5,6 at max_threads = 8,
identically on both analyzers.

Validation never caught it because window PARTITION BY routes through
validateGroupByKeyType, which only rejects Dynamic and Variant, rather than
through validateSortingKeyType, which carries the comparability check. Both
analyzers are guarded here, since guarding only one leaves enable_analyzer = 0
silently returning the wrong result.

The predicate is the existing helper hasAggregateFunctionType rather than a
comparability predicate. It matches the reported defect exactly, it already
performs the forEachChild recursion the Array, Tuple and Map forms need, and it
excludes SimpleAggregateFunction structurally, that type being a custom name on
its comparable storage type. A comparability predicate would additionally
reject QBit, which partitions correctly and stably today, for no reason the
report asks for; that is deliberately not done. GROUP BY and DISTINCT over an
aggregate state are accepted and stable, so the shared validateGroupByKeyType
helper is deliberately left alone and the new check lives beside it.

Two boundaries are deliberate and are asked about in the issue thread. A state
reached through Dynamic is not covered, DataTypeDynamic exposing no children,
and it is reachable only with allow_suspicious_types_in_group_by = 1, whose own
error text already warns about unexpected results. Window ORDER BY over a state
is still accepted by the old analyzer; a comparability guard there would newly
reject QBit, so that gap is left for the component owner to rule on.

A state inside Variant is refused, because DataTypeVariant does expose its
variants as children. That asymmetry with Dynamic follows from the two types'
forEachChild implementations and is pinned by the test.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent reviewer read the change cold, without the author's evidence, and a separate
reviewing model then re-reviewed the full diff. Verdicts below.

No finding on the code. The reviewer's own carrier enumeration, done before reading the
author's plan, agreed with it: the two guarded sites are chokepoints (resolveWindow has 2
callers, both reaching the guarded loop; makeWindowDescriptionFromAST has 2 callers, both inside
makeWindowDescriptions, whose single caller is ExpressionAnalyzer.cpp:2255), the third
WindowDescription producer consumes an already-validated WindowNode, and
mergeWindowWithParentWindow copies only a parent list that was itself validated. The
second-model pass returned 0 findings and its diffstat matched the intended change set.

Because a new analysis-time throw in a Backward Incompatible Change can break server startup,
the reviewer swept the attach paths separately. Views do not re-analyse their stored SELECT at
attach (InterpreterCreateQuery computes a sample block only when there is no columns list, and an
attached view always has its normalized one; SelectQueryDescription::getSelectQueryFromASTForMatView
runs no analyzer). Projections do re-analyse at attach, but cannot contain a window function:
ParserProjectionSelectQuery parses no WINDOW clause and the path it uses asserts no windows.
So the only newly-throwing surface is a live query, which is the intended change.

⚠️ Two countable claims in this PR's own text were wrong, both overstating coverage, and both are
corrected above rather than re-measured, the underlying evidence being sound.

  • The blast-radius positive control was published as "86 files matching OVER (PARTITION BY".
    86 is a working-tree count and two of those files are gitignored *.stdout artifacts that this
    change's own test runs wrote. Committed content measures 83 at master and 84 in the merged
    tree. The blast-radius figure itself is unaffected: the AggregateFunction predicate scores 0
    against both the working tree and master.
  • The regression slice was published as "86 tests on both binaries". The fixed binary ran 86 and
    the parent ran 85; the extra one is the new test, which cannot exist on the parent. Over the
    85 they share, the failure sets and reason buckets are identical, 5 on each arm, nothing
    only-in-fix, which is the comparison the claim rests on and which re-derives exactly.

💡 One nit the reviewer raised was dropped on its own evidence: dense_rank() was flagged
against the repository convention that function names are written without parentheses, but that
convention explicitly applies "when it refers a function itself rather than its application", and
both uses here refer to the fixture's call. Repository practice over the last 300 commit messages
agrees.

Two boundaries are deliberate, disclosed in the description and asked in the issue thread rather
than decided here: a state reached through Dynamic is uncovered because DataTypeDynamic exposes
no children, and window ORDER BY over a state is still accepted by the old analyzer, where a
comparability guard would newly reject QBit. Both are pinned by test rows and by mutants, so
neither can be closed silently.

Session id: cron:clickhouse-review-slot-8:20260807-182500

@groeneai

groeneai commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Check Answer
a Deterministic repro? Yes. The reporter's fixture, max_block_size = 2 (load-bearing), only max_threads differing: dense_rank() gives 1,1,2,3,4,5,6,7,8 at max_threads = 1 and 1,1,2,3,1,4,2,5,6 at max_threads = 8, on both analyzers, 4 of 4 arms deterministic. The difference between the two arms is the witness; one arm alone cannot show a path disagreement.
b Root cause explained? AggregateFunction does not override IDataType::isComparable (default false, IDataType.h:235). The sort path calls ColumnAggregateFunction::compareAt, a stub returning 0 unconditionally (ColumnAggregateFunction.h:235), so all states compare equal and collapse into one partition; ScatterByPartitionTransform instead hashes their raw bytes and scatters them. max_threads picks the path. Validation missed it because window PARTITION BY routes through validateGroupByKeyType (QueryAnalyzer.cpp:2965, ExpressionAnalyzer.cpp:689), which rejects only Dynamic and Variant (validateGroupByKeyType.cpp:20), not through validateSortingKeyType, which carries the comparability check (QueryAnalyzer.cpp:3939, ExpressionAnalyzer.cpp:1787). Every file:line pair cited in this comment was verified against origin/master 2999ffda752d by fragment match, 13 OK / 0 BAD, with negative controls on other lines of the same files correctly reporting no match. That count treats the two abbreviated line references in row (i) as citations of the file named just before them, so a grep for the fully written file:line form finds 11 rather than 13.
c Fix matches root cause? The defect is that validation accepts the query, so the fix is at validation. No bound widened, no dataset shrunk, no test tagged out, no defensive check at the crash site. 33 added source lines across 4 files, 24 of them non-comment.
d Test intent preserved / new tests added? No existing test is touched: grep -rliE "PARTITION BY[^)]*(uniqState|AggregateFunction|anyState|sumState)" tests/queries/0_stateless/ returns 0 files, with a positive control of 84 files under that directory matching OVER (PARTITION BY at origin/master, 85 in the merged tree. The same query for a window ORDER BY over a state returns 0 files at origin/master, with a positive control of 98 files matching OVER ( followed by ORDER BY. New test 04817_window_partition_by_aggregate_function_state carries 40 serverError assertions, of which 9 are the refusals this round adds: those 9 are exactly the rows that still succeed on the parent commit, and exactly the rows that reverting the new guard makes succeed again (mutant M6). The remainder were already refused before this round (top-level ORDER BY over a bare state and over a state stored in a SimpleAggregateFunction, and the Dynamic/Variant gate, each on both analyzers), plus 26 positive-count assertions, which is exactly the number of value lines in the reference file. Every row runs on both analyzers.
e Demonstrated in BOTH directions? Yes. The test is [ FAIL ] on the parent commit's binary and [ OK ] with the change, each run against a server whose SELECT lower(buildId()) was asserted equal to the binary's readelf -n value first. Base 0502ee8df849bfcb43, fixed 44dc69f37618bf4a.
f General across CODE paths? Both analyzers are guarded for both window clauses, and mutants M1, M2 and M6 prove each site independently: reverting the new-analyzer guard stops the refusal only on the new-analyzer rows, reverting the old-analyzer guard only on the old-analyzer rows, an exact mirror of 8 rows each. The third WindowDescription producer, extractWindowDescriptionFromWindowNode (PlannerWindowFunctions.cpp:33), needs no guard because it consumes an already-resolved WindowNode validated at QueryAnalyzer.cpp:2965. makeWindowDescriptionFromAST has exactly 2 call sites, both in makeWindowDescriptions, whose only caller is ExpressionAnalyzer.cpp:2255, so the old-analyzer site is a chokepoint.
g Generalizes across INPUTS? Refused: bare state, Array, Tuple, Map, Array(Tuple(...)) at depth 2, Variant, and a multi-key PARTITION BY id, st. Also refused: SimpleAggregateFunction(any, AggregateFunction(uniq, UInt64)), whose storage type is the state itself, so hasAggregateFunctionType reaches it; that form carries the same max_threads instability as a bare state, 1,1,2,3,4,5,6,7,8 against 1,1,2,3,1,4,2,5,6, and top-level ORDER BY over it was already refused before this change, so both are now pinned on both analyzers. Still accepted: SimpleAggregateFunction(sum, UInt64), whose storage type is UInt64, QBit, Array(QBit), String, LowCardinality, Nullable, plain Dynamic with the opt-in, and GROUP BY and DISTINCT over a state. Mutant M3 (a non-recursive predicate) stops the refusal on every wrapper row, Array, Tuple, Map, Array(Tuple(...)) and Variant on both analyzers, while the bare-state row stays green, which pins the recursion.
h Backward compatible? Deliberately not: this is a Backward Incompatible Change, a query that runs today starts throwing, which is the point of the issue. No default moves and no setting is added, so no SettingsChangesHistory.cpp entry is owed, matching PR 105450, whose 6 changed files do not include it. The category was validated by running the repo's own get_category, which returns pr-backward-incompatible, with both negative controls reddening.
i Invariants and contracts preserved? The new function reads a DataTypePtr and throws; it holds no state, takes no locks, allocates nothing and runs at analysis time before any pipeline exists, so there is no error path or partial-execution concern. GROUP BY's contract is untouched: the check is a separate function rather than an addition to the shared validateGroupByKeyType, which also serves GROUP BY (QueryAnalyzer.cpp:4092, :4111, :6675, ExpressionAnalyzer.cpp:1485), and GROUP BY and DISTINCT over a state were measured accepted and stable at max_threads 1 and 8. The pre-existing ORDER BY and Dynamic/Variant refusals were verified unchanged.

Mutation matrix, each mutant built with its Build ID recorded, run, then restored; after restore the shipping Build ID returned byte-exactly, which is what proves the mutants ran on different binaries:

Two failure modes appear below and they are not interchangeable. A mutant that makes an
expected refusal stop happening is reported per row: the runner records every such row and
finishes the file, so the reddened set can be read exactly. A mutant that makes a query throw
where none was expected aborts the file at that query, so the rows after it are never run;
those are reported as an abort with the offending message and the count of unrun assertions.

mutant mode observed conclusion
M1, revert the new-analyzer guard per row 6 new-analyzer witnesses plus the new-analyzer Variant and SimpleAggregateFunction rows stop refusing, 8 rows; all 6 old-analyzer witnesses stay green that site is load-bearing
M2, revert the old-analyzer guard per row the exact mirror, 8 rows, distinguished by which analyzer section they sit in rather than by query text that site is load-bearing, and neither covers the other
M3, drop the recursion per row 10 rows: Array, Tuple, Map, Array(Tuple(...)) and Variant on both analyzers; the bare-state row stays green on both the recursion is load-bearing, and the asymmetry is the demonstration
M4, use !isComparable() instead abort Data type QBit(BFloat16, 16) is not allowed in window PARTITION BY keys, on the first QBit control; 15 later assertions not run the scope is deliberately narrower than general comparability
M5, also fire on Dynamic abort Data type Dynamic is not allowed in window PARTITION BY keys, on the first opt-in Dynamic control; 10 later assertions not run the uncovered Dynamic case is a deliberate boundary, not an oversight
M6, revert the new old-analyzer window ORDER BY guard per row 9 rows stop refusing: the five state-typed sort keys, the combined PARTITION BY id ORDER BY st, the named WINDOW and derived-window forms, and the SimpleAggregateFunction-stored state; every other row stays green on both analyzers that site is load-bearing and no other guard covers it

Suite: 50 randomized and 50 plain runs of the new test, 50 OK each, counted from per-test verdict lines. A 162-test window slice ran on both binaries. Six tests fail deterministically on each, identically: five are cluster or connectivity cases on this bare single-node server (Code: 210 Connection refused, Code: 279 All connection tries failed) and 04105_limit_by_into_sort_explain is a reference mismatch, all present on the unmodified binary. Three further tests reverse verdict between runs on both binaries under load, so they are load-dependent and unrelated to this change. Nothing fails only on the fixed binary. 04259_window_partition_by_dynamic_variant_validation, the test of the precedent this mirrors, stays green.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @Avogar, could you review this? Window PARTITION BY routes through validateGroupByKeyType, which checks only Dynamic and Variant, rather than through validateSortingKeyType, which carries the comparability check, so an AggregateFunction key was accepted and then partitioned by whichever path max_threads picked: the sort path sees every state as equal via a compareAt stub, the scatter path hashes their bytes.

@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a1ae82e]

Summary: ✅


AI Review

Summary

This PR closes the wrong-results hole where window PARTITION BY and old-analyzer window ORDER BY accepted aggregate-function states and could produce thread-count-dependent results. The aggregate-state coverage itself looks correct, but the new old-analyzer window ORDER BY validation still leaves one existing key-type contract unimplemented, so I cannot approve it as-is.

Findings

⚠️ Majors

  • [src/Interpreters/ExpressionAnalyzer.cpp:721] The old-analyzer window ORDER BY path now blocks aggregate states, but it still bypasses allow_suspicious_types_in_order_by for Dynamic and plain Variant keys. Ordinary ORDER BY already rejects those types via validateOrderByKeyType, and the analyzer does the same for window ORDER BY, so enable_analyzer = 0 still disagrees on the only remaining validation site for this carrier. Please enforce that setting contract here as well and add a regression row for row_number() OVER (ORDER BY d) / Variant.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: make old-analyzer window ORDER BY honor the existing allow_suspicious_types_in_order_by contract for Dynamic/Variant, and cover it with a focused regression test.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-backward-incompatible Pull request with backwards incompatible changes label Aug 7, 2026
… rule

Two section markers of the new test said `new analyzer`, which the
`check_style` analyzer-wording rule forbids: the analyzer has been the
default since 24.3 and is no longer new. The rule is implemented in
`ci/jobs/scripts/check_style/various_checks.sh` and matched
`04817_window_partition_by_aggregate_function_state.sql` at lines 29 and 47,
failing `Style check` and, because praktika will not schedule the matrix
behind a red gate job, dropping every downstream check on the previous head.

Both markers now say `the analyzer`, and their two counterparts in the
`.reference` file are updated in the same change so the recorded output
still matches byte for byte. Nothing else moves: no assertion is added,
removed or weakened, no `src` file is touched, and the built binary is
unchanged.

Verified on identity-asserted debug servers, that is with the `readelf`
build id equal to what `SELECT lower(buildId())` reports before any verdict
is taken: the test passes on this tree and still fails on the parent commit
for its original reason, every state-carrying row succeeding where error 44
was expected. All five mutants were re-run against the corrected test rather
than trusting the earlier logs, since those logs are keyed on the marker text
that just moved, and each is still caught by exactly the rows meant to catch
it, with the same counts as before.
`SimpleAggregateFunction` is a custom name on its storage type, and that
storage type may itself be an aggregate function state:
`SimpleAggregateFunction(any, AggregateFunction(uniq, UInt64))` reports
`AggregateFunction(uniq)` from `toColumnTypeName`. `hasAggregateFunctionType`
therefore reaches it and the new guard refuses a window `PARTITION BY` over
such a column, which the changelog entry did not say and no test pinned.

The refusal is right rather than incidental. On the reporter's fixture with
the state stored that way, `dense_rank` gives `1,1,2,3,4,5,6,7,8` at
`max_threads = 1` and `1,1,2,3,1,4,2,5,6` at `max_threads = 8`, byte for byte
the instability reported for a bare state, on both analyzers. Top-level
`ORDER BY` over the same column was already refused with the same error code
before this change, so refusing the partition key restores the same symmetry
this change restores for a bare state.

The test now pins the form on both analyzers: the two `PARTITION BY` rows
fail on the parent commit, each reporting that the query succeeded where
error 44 was expected, while the two `ORDER BY` rows pass there, which is
what shows the pre-existing half is untouched. `SimpleAggregateFunction` over
an ordinary type keeps its own control row and stays accepted, because its
storage type carries no state.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

Two commits pushed, and one of them corrects the scope of the changelog entry, so it is worth flagging for anyone who already started reading.

Style check was red on the previous head: two section markers of the new test said new analyzer, which the check_style analyzer-wording rule forbids. Both markers and their two counterparts in the .reference file now say the analyzer. Because praktika will not schedule the matrix behind a red gate job, that red had dropped every downstream check, so nothing else had actually run on that head.

While re-verifying, a case turned out to be refused that the changelog entry claimed was unaffected. SimpleAggregateFunction is a custom name on its storage type, and that storage type can itself be a state: SimpleAggregateFunction(any, AggregateFunction(uniq, UInt64)) reports AggregateFunction(uniq) from toColumnTypeName, so hasAggregateFunctionType reaches it and the guard refuses a window PARTITION BY over such a column.

The refusal looks right rather than incidental. With the reporter's fixture storing the state that way, dense_rank gives 1,1,2,3,4,5,6,7,8 at max_threads = 1 and 1,1,2,3,1,4,2,5,6 at max_threads = 8, byte for byte the instability reported for a bare state, on both analyzers; and a top-level ORDER BY over the same column was already refused with the same error code before this change. So the entry now says the refusal covers a state nested in SimpleAggregateFunction as well, and the test pins the form on both analyzers: its two PARTITION BY rows fail on the parent commit while its two ORDER BY rows pass there, which is what shows the pre-existing half is untouched. SimpleAggregateFunction(sum, UInt64) keeps its own control row and stays accepted.

If you would rather that form stayed accepted, say so and I will narrow the predicate instead.

Comment thread src/Interpreters/ExpressionAnalyzer.cpp Resolved
The previous commits guarded window PARTITION BY on both analyzers, but the
old analyzer's window ORDER BY branch validated no sort-key types at all, so
row_number() OVER (ORDER BY st) with enable_analyzer = 0 still reached the
aggregate-state sort path. There ColumnAggregateFunction::compareAt reports
every pair equal, so all rows tie: rank() OVER (ORDER BY st) over nine
distinct states returned nine 1s, while ORDER BY id over the same table
returned 1 to 9 and the analyzer refused the same query with ILLEGAL_COLUMN.
Order-dependent window functions were therefore silently wrong in a
supported mode.

validateWindowPartitionByKeyType becomes validateWindowKeyType and takes the
clause name, so the same aggregate-state-specific predicate now runs for both
window clauses and each error message names the clause it came from. Keeping
the predicate specific to hasAggregateFunctionType, rather than reusing the
comparability check that ORDER BY employs, is what avoids widening the
rejection: QBit is incomparable but is not a state, so the old analyzer keeps
accepting OVER (ORDER BY q) exactly as before, which a new control row pins.
Top-level ORDER BY over a QBit was already refused on both analyzers, so no
form that works today stops working.

The guard sits in makeWindowDescriptionFromAST next to the PARTITION BY one,
which also covers a named WINDOW clause and a window derived from one: a
derived window copies an already-validated parent and is refused if it tries
to override a non-empty ORDER BY.

Measured on debug builds of the parent and of this commit, with each server's
buildId asserted against readelf before any verdict. Nine new assertions
redden on the parent and pass here; reverting only the new guard reddens
exactly those nine and nothing else. A 162-test window slice run on both
binaries has the same six deterministic failures on each, all pre-existing
distributed-cluster cases; three further tests reverse verdict between runs
on both binaries under load and are unrelated to this change. No test in the
tree sorts a window by an aggregate state, so nothing is reddened upstream.
@groeneai groeneai changed the title Reject window PARTITION BY over an aggregate function state Reject window PARTITION BY and ORDER BY over an aggregate function state Aug 8, 2026
for (const auto & col : actions_dag->getResultColumns())
{
if (col.name == sort_key_name)
DB::validateWindowKeyType(col.type, "ORDER BY");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This closes the aggregate-state hole, but this old-analyzer window ORDER BY path still never applies the existing allow_suspicious_types_in_order_by contract. Dynamic and plain Variant keys have no aggregate state, so they still fall through here with enable_analyzer = 0, while ordinary ORDER BY already rejects them via validateOrderByKeyType and the analyzer does the same for window ORDER BY.

Because makeWindowDescriptionFromAST is the only validation site for old-analyzer window definitions, this carrier is still out of sync after the PR. Please enforce the Dynamic/Variant check here as well, and add a focused regression row for row_number() OVER (ORDER BY d) / Variant.

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.

The observation is correct and I verified it, but I am not fixing it in this PR, because it is pre-existing and out of scope, and the specific remedy suggested would undo a property this PR was written to preserve.

Measured on debug builds of the parent and of a1ae82e72582469, each server's buildId asserted against readelf before any verdict, over a Dynamic column and a Variant(UInt64, String) column:

query enable_analyzer = 1 enable_analyzer = 0
top-level ORDER BY d Code: 44 Code: 44
OVER (ORDER BY d) Code: 44 returns rows
OVER (ORDER BY v) Code: 44 returns rows
OVER (PARTITION BY d) Code: 44 Code: 44

Every cell is identical on the parent and on this commit. The gap you describe is real, but it predates this change, and the diff contains no reference to isDynamic, isVariant or allow_suspicious_types_in_order_by. This PR closes the aggregate-state hole in that branch; it does not claim to bring the branch up to the full sort-key contract.

The suggested remedy is what makes this a scope decision rather than an oversight. validateOrderByKeyType bundles the Dynamic/Variant check with an isComparable check in the same lambda, so calling it here also rejects any incomparable key. DataTypeQBit overrides isComparableForEquality but not isComparable, so OVER (ORDER BY q) would start failing in the old analyzer. Avoiding exactly that is why the guard added here is hasAggregateFunctionType rather than a comparability predicate, and a control row pins QBit as accepted. Splitting the lambda to take only the Dynamic/Variant half is possible, but that is a second backward-incompatible change to a different type family, policing 116 tests that pair a window with an ORDER BY, and it belongs in its own PR with its own changelog entry rather than riding along in this one.

I have not filed a follow-up task for it, since it is a maintainer's call whether the old-analyzer window ORDER BY branch should carry the full contract. If the answer is yes, it is a small change on top of the helper this PR introduces.

That is two rounds on this thread, so I will leave further direction here to a human reviewer rather than keep iterating.

@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a1ae82e72 with master c8cea90a1 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2999ffda7; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.38 MiB 687.39 MiB -2.99 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

502 object files changed (+309.22 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/HiveTextRowOutputFormat.cpp.o new 148.12 KiB +148.12 KiB
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationMap.cpp.o 2.16 MiB 2.18 MiB +21.09 KiB (+0.96%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationArray.cpp.o 228.85 KiB 249.85 KiB +21.00 KiB (+9.18%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationTuple.cpp.o 271.66 KiB 292.33 KiB +20.66 KiB (+7.61%)

737 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

70 translation units recompiled, 92 s compile time in total, 9 of them have a recent master baseline.

Translation units without a recent master baseline:

  • contrib/s2geometry-cmake/__/s2geometry/src/s2/s2builder.cc: 5.5 s

Job report

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a1ae82e

CI is fully finished on this head and there is nothing to own: 175/175 check-runs completed, 155 success, 20 skipped, 0 failures. Config Workflow and Finish Workflow both completed successfully.

Check / test Reason Owner / fixing PR
(none) no failing check on this commit not applicable

Read from the paginated check-runs API rather than the status rollup, which truncates on this repo, and corroborated independently against the CI database: 330,790 result rows are recorded for this commit across 157 checks with 0 rows in FAIL/ERROR. The two failures earlier on this PR belong to superseded heads and not to this one: Style check on 5f703246bf35 (fixed by the following push) and Build (arm_release) / Post Hooks on 7bcf837f326f (the CI telemetry step could not reach the logs cluster, which is infrastructure rather than this diff, and it does not recur here).

No Sync check ran on this commit, so there is no CH Inc sync line. I am not re-pinging reviewers.

Session id: cron:our-pr-ci-monitor:20260808-080000

@alexey-milovidov alexey-milovidov left a comment

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.

Sounds ok.

@alexey-milovidov alexey-milovidov self-assigned this Aug 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 15, 2026
Merged via the queue into ClickHouse:master with commit 3b9fd55 Aug 15, 2026
179 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 15, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
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 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.

4 participants