Repository navigation
Conversation
…hange A window aggregate of the CrossTab family (cramersV, cramersVBiasCorrected, contingency, theilsU) segfaulted in DB::CrossTabCountsState::merge under make_distributed_plan = 1 with distributed_plan_execute_locally = 1. Those four functions are the only ones with two state layouts behind one type name, selected by getStateVariant(). Nothing a header announces distinguishes them: neither the type name nor the binary type encoding a plan header uses carries the variant, deliberately, because all variants of one function share the serialization format. ExchangeViaChunks forwards a producer Chunk unchanged while the consumer advertises a header built independently of it, and a Chunk carries columns only, so a state produced as the Window representation could arrive under a header naming the Aggregation one. With the window step below a sorted gather, MergedData then builds its destination columns from that header and merges the foreign states into them. CrossTabPhiSquaredWindowData does not derive from CrossTabCountsState and keeps a Float64 where count_a sits, so the HashTable's buffer pointer read out of it is garbage and begin() dereferences it. theilsU's window state keeps the ordinary state's leading members, which is why it survived the same path. The serialized exchange leg already reconciled exactly this, in NativeReader. The in-memory leg now does the same: the exchange records the producer's header, and the source converts, with castColumn, any column for which the two headers differ only in the state representation. The set of such columns is resolved once and is empty for every stream whose announced types already agree, so unaffected queries pay a single test per chunk. Both legs share one whole-type predicate, differsOnlyByAggregateStateVariant, so they cannot drift apart and a state nested in a container type is covered as well; a missing producer header throws instead of failing open, which would recreate the inconsistent pair. Fixing the exchange rather than the crash site is deliberate: the defect is the inconsistent header/column pair, and the exchange is the only place a chunk changes owner between two independently built headers. A guard in ColumnAggregateFunction would sit below the defect and would not protect consumers that never insert, such as AggregateFunctionMerge::add, which takes its function from the declared argument type and has no second column to compare against. Reported for the AST fuzzer (amd_debug) failure on ClickHouse#118287 at 1029303. Co-Authored-By: Claude Opus 5 <[email protected]>
The test's plan-shape self-check compared only the positions of the sorted gather and the window step. minIf returns 0 when nothing matches rather than NULL, so with the GatherExchange line absent the comparison degenerated to 0 < window row number, which holds whenever the window step is not the plan root: the guard kept passing while covering nothing. Measured on the previous revision of the file, a gather pattern matching no plan line still produced 1 and the test passed. Assert with countIf that both plan nodes are present before comparing their positions, so the file fails if the window stops being pushed below a sorted gather. The reference output is unchanged, and each of the two patterns fails the test on its own when corrupted. Also tighten the doc comment on convertAggregateStateVariants to three lines. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 findings), plus my own cold review
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260911-062400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260911-040700 |
|
Workflow [PR], commit [4b56432] AI ReviewSummaryPR #119401 restores aggregate-state variants across exchanges, casts, and query-plan deserialization. At head Missing context / blind spots
Findings❌ Blocker — deserialize
Tests
Final Verdict❌ Block. Correct the finalized-header and interpolation-output variant boundaries, and run focused regression cases for both. |
|
cc @davenger @al13n321, could you review this? No header carries an aggregate function's state variant, so a CrossTab window state crossed the local in-memory exchange under a consumer header naming the ordinary aggregation representation and was read with the wrong layout, segfaulting in |
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 702605eEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
The 168 Session id: cron:our-pr-ci-monitor:20260911-120034 |
…mory-exchange-state-variant # Conflicts: # docs/resources/develop-contribute/native-protocol/format.mdx # src/DataTypes/DataTypeAggregateFunction.h
`-Map` was the only pass-through combinator without `canMergeStateFromDifferentVariant` / `mergeStateFromDifferentVariant`, so `castColumn` refused to convert its window states. Now that the in-memory exchange converts state variants, `theilsUMapState(...) OVER (...)` under `make_distributed_plan = 1` failed with CANNOT_CONVERT_TYPE (it returned correct results before), and `contingencyMap` / `cramersVMap` went from a segfault to the same error. The per-key loop is shared with `mergeImpl`. This also lets `-MapMerge` accept window-produced states, which was rejected with ILLEGAL_TYPE_OF_ARGUMENT before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
CI finish ledger - 59969f2Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261009-190009 |
|
Fixing PR for the |
…mory-exchange-state-variant # Conflicts: # docs/resources/develop-contribute/native-protocol/format.mdx # src/QueryPipeline/DistributedPlanExecutor.cpp
…l inputs The binary type encoding does not carry the aggregate state variant (Aggregation vs Window), so `ActionsDAG::deserialize` decoded every INPUT of a CrossTab-family window state as the Aggregation layout and built each function from that decoded type. A `_CAST` of such a state to `Variant`, `Dynamic` or `AggregateFunction` was then built as a relabelling instead of the converting cast the initiator's plan uses, its declared result type named the Aggregation layout, so no exchange could see the mismatch afterwards, and a later `-Merge` read the window layout as the aggregation one and segfaulted in `CrossTabCountsState::merge` (STID 2844-39f8, AST fuzzer oracle). `ActionsDAG::deserialize` now takes the headers of the streams the DAG is executed over. An INPUT whose decoded type differs from the actual column only by the state variant takes the actual type, when its name occurs exactly once across those headers (`updateHeader` binds the k-th input of a name to the k-th column of that name, and the input order is read only after the nodes). ALIAS and ARRAY_JOIN nodes, and FUNCTION results rebuilt from the retyped inputs, follow the same variant-only rule; a node with a deserialized constant keeps its type. This is what `WindowStep::deserialize` already does for its arguments. The plan steps that execute a DAG over their input streams pass `ctx.input_headers`; the other callers keep today's behaviour. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rename `05182_distributed_plan_window_state_variant_sorted_gather` to `05182_distributed_plan_window_state_variant`, since it now covers both places where a CrossTab-family window state met a reader built for the Aggregation layout, and drop the `no-old-analyzer` tag (the old analyzer and that tag are gone). New sections, each distributed and then with `make_distributed_plan = 0`: the fuzzer's shape (a Variant of a window and an ordinary state, read through its subcolumn and merged), a cast to `Dynamic`, a cast to the state type, and a plain `contingencyMerge` of the window state, plus a liveness row that is absent unless the Variant shape really distributes. The first three crash on master and with only the exchange conversion; the last one crashes on master. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ured columns A lambda that captures a window state inside a deserialized fragment was rebuilt with the captured, lambda-body input and return types decoded from the wire, which always name the Aggregation layout. `FunctionCapture::getArgumentTypes` returns the captured types, so when the fragment's header delivers the Window-variant column, `ActionsDAG::updateHeader` sees the argument types drift and leaves the lambda's column unknown, and the higher-order function above it throws `NOT_FOUND_COLUMN_IN_BLOCK` (e.g. `contingencyMerge(arrayElement(arrayMap(x -> s, [1]), 1))` over `contingencyState(b, c) OVER ()` with `make_distributed_plan = 1`). An aggregate function with a single state layout (`sumState`) never drifts. Each captured type now takes the variant of the matching child (the planner adds the children in captured-name order; a name mismatch leaves the decoded type), the lambda body is deserialized over the captured columns as its actual input header, and the capture's return type and the node's function type follow the body's output. Lambda argument types stay decoded: their real types belong to the higher-order function's other arguments. A captured lambda (a `Function`-typed capture) also keeps its decoded type. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `distributed_plan_fallback_to_local_execution` at its default, a query that stops distributing runs on the initiator and its distributed line equals its local line no matter what the fragment does. Pin it off for the session, like the other `make_distributed_plan` tests do. The liveness check over `EXPLAIN PIPELINE` is an aggregating query over `EXPLAIN` and cannot be distributed itself, so it now runs non-distributed and asks for the distributed plan only in the `EXPLAIN`, the same shape as the sorted-gather check at the top of the file. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…o their wire types Adopting the Window state variant from the actual input (32ab61b) also retyped the non-lambda arguments of higher-order functions, e.g. `array(s)` became `Array(Window)`, while the lambda next to it keeps the wire (Aggregation) argument type. A lambda's argument types are fixed by its consumer (`getLambdaArgumentTypes`), and the consumer is read from the stream after the lambda, whose body is already built (and may be JIT-compiled) for the decoded types, so it cannot be retyped there. `ColumnFunction::appendArgument` then threw `LOGICAL_ERROR` already in `updateHeader` for queries master answers, e.g. `arrayMap(x -> finalizeAggregation(x), [s])` over `contingencyState(b, c) OVER () ... LIMIT 1` with `make_distributed_plan = 1`. A non-capture FUNCTION node with a `Function`-typed child now gets every other child whose type was adopted replaced, for this node only, by an inserted `_CAST(child, '<wire type>')`, so the function and its lambda see the same types. The cast converts the Window state into the Aggregation layout (`mergeStateFromDifferentVariant`), which is what master already does for an `array(...)` literal, where `FunctionArray` casts to the declared element type. The nodes are inserted before their consumer, so the node list stays topological; other consumers of the same child keep the Window type. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…state variant test S0 asserts that the Cascades plan of such a query is distributed, so the two sections after it cannot pass vacuously on a local plan. S1 is the AST fuzzer's query shape (`-Merge` after `LIMIT BY` over a window state), which segfaulted on master and on the previous head. S2 is `-MergeArray` over an array of window states, which worked on master and segfaulted on the previous head. Both compare against the non-distributed plan. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`differsOnlyByAggregateStateVariant` holds, by the binary type encoding, for a state whose argument is a window state, e.g. `groupArrayState(s) OVER (...)` over `s = contingencyState(b, c) OVER (...)`. The in-memory exchange and `NativeReader` then cast such a column, but `CAST` could neither relabel it (`haveSameStateRepresentation` compares the state types, whose argument types differ by the variant) nor convert it (`groupArray` has no `canMergeStateFromDifferentVariant`). So the query failed with CANNOT_CONVERT_TYPE when the column was returned through the gather of a distributed plan or read back from a spilled sort; master segfaulted in the first case and failed with TYPE_MISMATCH in the second. Relabel when both functions have the same state variant, their argument types differ, and the encodings are identical. An aggregate function's own state does not depend on the variant of its arguments: a generic aggregate keeps an argument as its serialized value, and a window state serializes in the Aggregation format. Found by the automated review of the previous head. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…te variant test A scalar subquery returns `groupArrayState` over a window state through the sorted gather of a distributed plan, so the state itself crosses the exchange (a finalized projection would be computed below it). The second pair spills a sort over such a state. Both failed with CANNOT_CONVERT_TYPE on the previous head; on master the first segfaulted and the second failed with TYPE_MISMATCH. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…indow state variant test A Cascades plan keeps the window and the join on one node, so a join condition over a window state is deserialized with the window variant adopted, and a cast back to the wire type is inserted for the argument of the higher-order function in it. The join step resolves its nodes by their serialized ids; resolving them by position in the final node list (the earlier behaviour) shifts every node after the inserted cast and fails with CANNOT_PARSE_BOOL. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review of this update (the
Round 2 (the two fixes above): no findings from either review. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20261025-210800 |
|
cc @nickitat, could you review the aggregation part of this update? Under |
…ant by a round trip Relabelling such a state kept the memory layout of the source arguments. That is wrong for an aggregate that keeps its argument in a column: `any`, `anyLast` and the result of `argMin`/`argMax` keep a value with `Dynamic` in a column, so a window state inside it stayed in the Window layout while the target function read it as the Aggregation layout. Finalizing or merging the cast state then segfaulted in CrossTabCountsState::merge, e.g. for `CAST(anyState(tuple(s, CAST(1 AS Dynamic))) AS AggregateFunction(any, Tuple(AggregateFunction(contingency, UInt32, UInt32), Dynamic)))` over a window `s`. Master rejected that cast with CANNOT_CONVERT_TYPE. Serialize every state with the column's own function and deserialize it with the target function. The binary format of a state does not depend on the state variant of a state in its arguments, because a window state serializes in the Aggregation format. The column's function is used rather than the source type's, because a column may have been deserialized through a pooled serialization of the other variant. Found by the automated review of the previous head. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…of their arguments `SerializationAggregateFunction` objects are pooled by a hash of the state type name, the type name, the version and the function's own state variant. Two functions whose arguments differ only by the variant of a nested state, e.g. `any` of `Tuple(AggregateFunction(contingency, ...), Dynamic)` built over a window state and the same type parsed from its name, have the same hash, so both types got one serialization holding one of the two functions. A column of the other type was then written or read with the wrong argument layout. Through a spilled sort, with the CAST fix alone, about 1 run in 10 segfaulted while writing the spilled block; on the previous head every run returned a wrong result or segfaulted; on master the query failed with TYPE_MISMATCH and, rarely, segfaulted. Hash the state variants of the aggregate states nested in the argument types as well, the same way the function's own variant is hashed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he window state variant test `any` of a value with `Dynamic` keeps the window state in a column. The section casts such a state to the type named in SQL and finalizes it, serializes it in one tuple next to the original state (the tuple holds the serializations of both elements at once) and sorts it through an external sort, spilled and not spilled. On the previous head the first two segfaulted and the spilled sort returned a wrong result or segfaulted; with only the CAST fix the second segfaulted; on master the cast failed with CANNOT_CONVERT_TYPE and the spilled sort with TYPE_MISMATCH. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ut state column Merging steps rebuild their deserialized aggregates from the wire-encoded argument types, which do not carry the aggregate state variant. Their input holds the aggregate's states rather than its arguments, so the argument-column rule added for `AggregatingStep` never applied to them. With a single-worker Cascades plan they run in the same stage as the aggregation that built the states, with no exchange to convert them in between. A state such as `any(tuple(s, CAST(1 AS Dynamic)))` over a window state `s` keeps `s` in a column, so finalizing it inserted Window-layout states into a column of the Aggregation function and merged them as such: `GROUP BY p, b WITH ROLLUP` / `WITH CUBE`, and the merge-only aggregation that `AggregationPushdown` leaves above a join, segfaulted in `CrossTabCountsState::merge`, while `make_distributed_plan = 0` answered. When an argument's own column is not in the input, take the type from the matching argument of the aggregate's state column if the two differ only by the state variant. All steps that deserialize aggregate descriptions now pass their input header (`MergingAggregated` and `TotalsHaving` too; their input reaches them through an exchange, or not at all with `WITH TOTALS`, so they see the decoded types and nothing changes there). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ades stage in the window state variant test `any` of a tuple with `Dynamic` keeps the window state in a column. The new sections merge such states in the same single-worker Cascades stage as the aggregation that built them: into the multi-row subtotals of `GROUP BY p, b WITH ROLLUP` and `WITH CUBE`, and in the merge-only aggregation above a join that `AggregationPushdown` builds (statistics hints steer the plan to it; the section asserts the plan shape). On the previous head all three segfaulted in `CrossTabCountsState::merge`; on master the distributed plan already segfaulted in the aggregation. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…differ by a round trip A window state over another window state, e.g. `contingencyState(s, v) OVER ()` over a window `s`, is read back from a spilled sort with both its own state and the state in its arguments in the Aggregation representation. The round trip required the outer variants to be equal, and `canMergeStateFromDifferentVariant` rejects the unequal argument types, so the read threw `CANNOT_CONVERT_TYPE` from `BufferingFromFileSource`. An explicit `CAST` of such a state to its printed type failed the same way. All variants of one function serialize the same way, so the round trip does not need the outer variants to be equal. Found by the automated review of the previous head. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
|
||
| actions_dag = ActionsDAG::deserialize(ctx.in, ctx.registry, ctx.context, ctx.max_type_complexity); | ||
| actions_dag = ActionsDAG::deserialize( | ||
| ctx.in, ctx.registry, ctx.context, ctx.max_type_complexity, /*nesting_depth=*/ 0, ctx.input_headers); |
There was a problem hiding this comment.
❌ Restore the finalized input types before deserializing HAVING
When final is true, this is not the header on which the DAG executes: TotalsHavingTransform::transformHeader and transform finalize the aggregate columns first. For example, the incoming column for any(s) is AggregateFunction(any, AggregateFunction(contingency, UInt32, UInt32)), with a Window variant in its argument, whereas the DAG input for any(s) is the inner AggregateFunction(contingency, UInt32, UInt32). These differ by more than the variant, so adopt_state_variant leaves that DAG input in the decoded Aggregation variant.
Consequently, a CAST(any(s) AS AggregateFunction(contingency, UInt32, UInt32)) in HAVING is prepared as an identity cast. At runtime finalization supplies a Window state, and the identity cast relabels it as Aggregation. Wrapping it in an array and calling arrayReduce('contingencyMerge', ...) then selects the ordinary merge for a Window pointer, retaining the invalid-layout read this PR fixes elsewhere.
Although make_distributed_plan rejects WITH TOTALS, ordinary serialize_query_plan can ship a complete IN subquery through SetsSerialization. A focused regression candidate using this PR's table is:
SELECT count()
FROM remote('127.0.0.2', currentDatabase(), t_window_state_variant_gather)
WHERE b IN
(
SELECT p
FROM
(
SELECT p, contingencyState(b, c) OVER (PARTITION BY p) AS s
FROM t_window_state_variant_gather
)
GROUP BY p WITH TOTALS
HAVING arrayReduce('contingencyMerge',
[CAST(any(s) AS AggregateFunction(contingency, UInt32, UInt32))]) >= 0
)
SETTINGS serialize_query_plan = 1, prefer_localhost_replica = 0,
make_distributed_plan = 0, enable_parallel_replicas = 0, max_threads = 1;Please derive the DAG's actual input header by finalizing the aggregate columns when final is true, while retaining the raw header for aggregate-description deserialization. Compare the case above with serialize_query_plan = 0. This is a source-level trace; no current-head executable was available to run it.
| { | ||
| auto actions = ActionsDAG::deserialize(ctx.in, ctx.registry, ctx.context, ctx.max_type_complexity); | ||
| auto actions = ActionsDAG::deserialize( | ||
| ctx.in, ctx.registry, ctx.context, ctx.max_type_complexity, /*nesting_depth=*/ 0, ctx.input_headers); |
There was a problem hiding this comment.
Passing the input headers restores variants on DAG inputs, but an interpolation expression can produce an ordinary aggregate state that the planner implicitly casts to the target column's Window type. Planner.cpp adds that cast with ActionsDAG::addCast, whose type-name literal does not encode the variant. After serialization, the cast therefore produces the Aggregation variant again; a constant-folded cast result also decodes as Aggregation and has no input from which to recover its Window type.
The input header still has the Window target when the window and filling steps are in one serialized stage. The output-type check below consequently throws INCORRECT_DATA for a valid interpolation, even though both types print identically. A focused source-level regression candidate using this PR's table is:
SELECT v, round(finalizeAggregation(s), 6)
FROM
(
SELECT v, contingencyState(b, c) OVER () AS s
FROM t_window_state_variant_gather
ORDER BY v WITH FILL
INTERPOLATE
(
s AS initializeAggregation('contingencyState', toUInt32(0), toUInt32(0))
)
)
SETTINGS make_distributed_plan = 1, distributed_plan_execute_locally = 1,
enable_cascades_optimizer = 1, distributed_plan_workers_num = 1,
distributed_plan_fallback_to_local_execution = 0;Please convert variant-only mismatched DAG outputs to their actual target types before the strict output validation, or otherwise preserve the internal cast's target variant. The conversion must change the state representation, rather than just relabel the type. Compare with make_distributed_plan = 0; no current-head executable was available to run this candidate.
nickitat
left a comment
There was a problem hiding this comment.
The CrossTab family keeps two state layouts under one type name that the type encoding does not tell apart
I think this whole idea was simply wrong. And from now on we will chase all the places when a mismatch can cause a segfault or type mismatch. I'm trying now a different fix that will keep Window layout only within WindowTransform.
|
Agreed. Keeping the window layout inside
Should I close this PR now, or keep it open until yours is up? |
|
@nickitat @groeneai I have a fix with the same idea in #128685 (draft): a function under |
|
Ok, let's close this one then. |
Related: #118287
Related: #120502
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a server crash when a window aggregate state of the
cramersV,cramersVBiasCorrected,contingencyortheilsUfamily, also under-Tuple, was passed between stages of a distributed query plan, merged within one stage by-Merge,WITH ROLLUP,WITH CUBEor above a join (e.g. withenable_cascades_optimizer = 1), or cast toVariant,Dynamicor the state type, undermake_distributed_plan = 1withdistributed_plan_execute_locally = 1. A spilled sort over such states, also in anArray, aTupleor another state, no longer fails withTYPE_MISMATCH.Description
AST fuzzersegfaulted inCrossTabCountsState::mergeon #118287, #120502 and #92472. On 26.9.19.9,contingencyMerge(CAST(s AS AggregateFunction(contingency, UInt32, UInt32)))overcontingencyState(b, c) OVER ()segfaults under the two settings above.What breaks. The CrossTab family keeps two state layouts under one type name that the type encoding does not tell apart. The in-memory exchange forwards a chunk under the consumer's header, and plan deserialization decodes every type as the aggregation layout, so a
_CASTrelabels a window state instead of converting it, and a-Mergereads it as the other layout.Fix. The exchange casts the producer's columns that differ only by the state variant, and
NativeReaderwhen reading a spilled block;CASTreserializes a state whose arguments differ only by the variant; pooled serializations keep the variants apart.ActionsDAGand aggregate deserialization take the step's input header: a decoded type that differs only by the variant from its column, or from a merged state column's argument, takes that type; a higher-order function casts such an argument back to its lambda's layout.-MapgetscanMergeStateFromDifferentVariant.Validation. Each test section fails on master or with a change reverted and matches the local plan; 50/50 runs pass, 1040 related tests are unchanged. After the exchange or a lambda, a finalized value can differ in the last bits.
Workflow [PR]
Sync PR [sync-upstream/pr/119401]