Repository navigation
Reject window PARTITION BY and ORDER BY over an aggregate function state - #113878
alexey-milovidov merged 4 commits into
Conversation
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.
Internal second-model reviewAn independent reviewer read the change cold, without the author's evidence, and a separate No finding on the code. The reviewer's own carrier enumeration, done before reading the Because a new analysis-time throw in a
💡 One nit the reviewer raised was dropped on its own evidence: Two boundaries are deliberate, disclosed in the description and asked in the issue thread rather Session id: cron:clickhouse-review-slot-8:20260807-182500 |
Pre-PR validation gate (a-i)
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
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 ( |
|
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. |
|
Workflow [PR], commit [a1ae82e] Summary: ✅
AI ReviewSummaryThis PR closes the wrong-results hole where window Findings
Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 25/25 (100.00%) · Uncovered code |
… 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.
|
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.
While re-verifying, a case turned out to be refused that the changelog entry claimed was unaffected. The refusal looks right rather than incidental. With the reporter's fixture storing the state that way, If you would rather that form stayed accepted, say so and I will narrow the predicate instead. |
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.
| for (const auto & col : actions_dag->getResultColumns()) | ||
| { | ||
| if (col.name == sort_key_name) | ||
| DB::validateWindowKeyType(col.type, "ORDER BY"); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes502 object files changed (+309.22 KiB total), 1 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units70 translation units recompiled, 92 s compile time in total, 9 of them have a recent master baseline. Translation units without a recent master baseline:
|
CI finish ledger - a1ae82eCI is fully finished on this head and there is nothing to own: 175/175 check-runs completed, 155 success, 20 skipped, 0 failures.
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 No Session id: cron:our-pr-ci-monitor:20260808-080000 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A window
PARTITION BYorORDER BYover anAggregateFunctioncolumn is now rejected withILLEGAL_COLUMN, as top-levelORDER BYover such a column already was. Previously such a query was accepted by at least one analyzer, and windowPARTITION BYpartitioned differently depending onmax_threads. The refusal also covers a state nested inArray,Tuple,Map,VariantorSimpleAggregateFunction. ASimpleAggregateFunctionover an ordinary type,QBit, andGROUP BYandDISTINCTover a state, are unaffected.Description
The two partitioning paths react differently to a state: the sort path calls
ColumnAggregateFunction::compareAt, a stub returning0unconditionally, so all states collapse into one partition, while the scatter path hashes their raw bytes and scatters them. On the reporter's fixturedense_rank()gives1,1,2,3,4,5,6,7,8atmax_threads = 1and1,1,2,3,1,4,2,5,6atmax_threads = 8.Validation missed it because window
PARTITION BYroutes throughvalidateGroupByKeyType, which rejects onlyDynamicandVariant, not throughvalidateSortingKeyType, which carries the comparability check. The old analyzer's windowORDER BYbranch validated no sort-key types at all, sorank() OVER (ORDER BY st)over nine distinct states returned nine1s 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
hasAggregateFunctionTyperather than a comparability predicate, which would also rejectQBit; control rows pin that for both clauses. It follows aSimpleAggregateFunctionto its storage type, soSimpleAggregateFunction(sum, UInt64)stays accepted whileSimpleAggregateFunction(any, AggregateFunction(uniq, UInt64))is refused.GROUP BYandDISTINCTover a state are stable and untouched, so the shared helper is unchanged. NoSettingsChangesHistory.cppentry is owed, as in PR 105450.Validated on debug builds with each server's
buildIdasserted 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 fromsystem.projectionsso its parts stop being used. An explicitATTACH TABLEof such a table instead fails withILLEGAL_COLUMNand leaves it detached until the next restart. The mergedDynamicandVariantequivalent, 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. TheORDER BYhalf 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
Dynamicshows the same instability but is not covered,Dynamicexposing no children; it needsallow_suspicious_types_in_group_by = 1, whose error text already warns about unexpected results. A state insideVariantis refused. Both pinned by the test.