Skip to content

Fix segfaults reading CrossTab window states in a deserialized query plan - #119401

Closed
groeneai wants to merge 29 commits into
ClickHouse:masterfrom
groeneai:fix-2844-4ada-in-memory-exchange-state-variant
Closed

groeneai wants to merge 29 commits into
ClickHouse:masterfrom
groeneai:fix-2844-4ada-in-memory-exchange-state-variant

Conversation

@groeneai

@groeneai groeneai commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118287
Related: #120502

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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, contingency or theilsU family, also under -Tuple, was passed between stages of a distributed query plan, merged within one stage by -Merge, WITH ROLLUP, WITH CUBE or above a join (e.g. with enable_cascades_optimizer = 1), or cast to Variant, Dynamic or the state type, under make_distributed_plan = 1 with distributed_plan_execute_locally = 1. A spilled sort over such states, also in an Array, a Tuple or another state, no longer fails with TYPE_MISMATCH.

Description

AST fuzzer segfaulted in CrossTabCountsState::merge on #118287, #120502 and #92472. On 26.9.19.9, contingencyMerge(CAST(s AS AggregateFunction(contingency, UInt32, UInt32))) over contingencyState(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 _CAST relabels a window state instead of converting it, and a -Merge reads it as the other layout.

Fix. The exchange casts the producer's columns that differ only by the state variant, and NativeReader when reading a spilled block; CAST reserializes a state whose arguments differ only by the variant; pooled serializations keep the variants apart. ActionsDAG and 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. -Map gets canMergeStateFromDifferentVariant.

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]

groeneai and others added 2 commits September 11, 2026 05:25
…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 findings), plus my own cold review
of the resulting tree (3 findings) before reading the implementation notes. The two AGREEd items went
back as a fix plan and were re-reviewed on the resulting commit 702605e8eed58: that round returned
0 findings from the independent model and 0 from my own cold read of the delta. The fix itself is
byte-identical across both rounds; only a test guard and a comment changed.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test's plan-shape self-check passes even when the sorted gather is absent, so a plan change could leave the file covering nothing (05182_distributed_plan_window_state_variant_sorted_gather.sql) AGREE, fixed @ 702605e8eed58 Raised independently by both reviews. minIf over zero matching rows returns the numeric default 0, not NULL (SingleValueData.cpp:170-175), so with the gather line gone the assertion degenerates to 0 < window_row_number. The guard now requires a positive match count for both plan nodes before comparing their positions, using the same countIf(...) > 0 idiom as 04837_distributed_plan_window_partition_shuffle.sql, and each literal was corrupted in turn to confirm the row flips to 0
2 ⚠️ The widened nested-container branch of the new type predicate has no test that would fail if it were reverted (src/Formats/NativeReader.cpp) DISAGREE Correct that it is untested, and no live test is constructible: the nested carrier was built twice, contingencyStateForEach([b], [c]) OVER (PARTITION BY p ORDER BY v) below a sorted gather and the same nested state forced through the NativeReader external-sort spill, and both produce identical, correct output with and without the branch, so no oracle separates the two revisions and any test added would pass either way. I kept the branch because the alternative is not a silent mislabel: recursiveLowCardinalityTypeConversion reaches the inner AggregateFunction pair, matches no branch and throws TYPE_MISMATCH "Cannot convert: X to X" (DataTypeLowCardinalityHelpers.cpp:307, the doubled name being an artifact of getName() never printing the variant), so if the shape ever becomes reachable the choice is convert or reject a valid query. Risk is bounded: the branch only widens what reaches castColumn, which accepts a cross-variant pair only when canMergeStateFromDifferentVariant holds and otherwise throws (FunctionsConversion.cpp:806-833). The spec sentence's nested clause is a property of the format, checkable by reading encodeAggregateFunction (DataTypesBinaryEncoding.cpp:272-281 writes the function name, parameters and argument types, and no variant, at any depth)
3 💡 The changelog category should be Critical Bug Fix because the report is a server crash DISAGREE The crash needs make_distributed_plan = 1 together with distributed_plan_execute_locally = 1, both non-default experimental settings (SettingsChangesHistory.cpp:820), so it is not the ordinary-use class that category is reserved for, and I do not select Critical Bug Fix on my own initiative. Bug Fix (user-visible misbehavior in an official stable release) is measured rather than assumed: the 26.7 and 26.8 branches both carry the CrossTab window state variant and make_distributed_plan
4 💡 resolvePositionsToConvert throws on a missing producer header but returns an empty conversion set when the two headers disagree on column count DISAGREE Noted, not changed. Making that throw as well would alter behaviour on a shape this fix does not address, which I would rather not do inside a crash fix; the positional indexing stays safe because the conversion set is empty in that case
5 💡 One doc comment in the exchange source ran to four lines, over the three-line ceiling I hold myself to AGREE, fixed @ 702605e8eed58 Tightened to three lines. It states a non-obvious invariant, so it was shortened rather than removed

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

Session id: cron:clickhouse-review-slot-9:20260911-062400

@clickhouse-gh clickhouse-gh Bot closed this Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on unpatched master, not intermittent. A contingencyState(b, c) OVER (PARTITION BY p ORDER BY v) window under make_distributed_plan = 1, distributed_plan_execute_locally = 1 with 8 buckets kills the server on every run. clickhouse local cannot host it: registerPlanSteps() runs only in the server, so a fragment there fails with Code: 47 ... Unknown query plan step: GatherReceive before reaching the bug.
b Root cause explained? Yes. ExchangeViaChunks forwards a producer Chunk unchanged while the consumer advertises an independently built header, and no header carries the aggregate state variant (all variants of one function share the serialization format). A contingency window state thus arrives under a header naming the aggregation variant; below a sorted gather MergedData builds destinations from that header and merges the foreign states in, and CrossTabPhiSquaredWindowData holds a Float64 where count_a sits, so HashTable::begin() dereferences garbage. Fault address 0x1, Access: read.
c Fix matches root cause? Yes. It fixes the component that creates the inconsistent header/column pair (the exchange), not the crash site. An earlier draft guarding ColumnAggregateFunction was dropped: it sits below the defect and cannot protect non-insertion consumers such as AggregateFunctionMerge::add. No widened bound, no no-random-* tag, no size reduction, no defensive check at the crash site.
d Test intent preserved / new tests added? New 05182_distributed_plan_window_state_variant_sorted_gather.{sql,reference}; no existing test weakened. It carries a plan-shape self-check (the sorted gather must sit above the window step) so a future plan change cannot leave it silently covering nothing, and theilsU, whose window state keeps the ordinary state's leading members, is the negative control.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (base 5124c91b, fix ee49f59e), and by value rather than by liveness: the test file kills the base server after printing its plan-shape row, and passes on the fix with the distributed result equal to the make_distributed_plan = 0 oracle for contingency, cramersV, cramersVBiasCorrected and theilsU.
f Fix is general across code paths? Both exchange legs now share one predicate; the serialized leg already reconciled this in NativeReader and is refactored onto the shared helper. The third IExchangeLookup only delegates to those two, so no sibling site is missed. Consumers are deliberately untouched and fixed transitively: MergedData::insertRows (the CI stack), ColumnAggregateFunction::convertToValues (the local stack), finalizeAggregation, AggregateFunctionMerge::add, Squashing.
g Fix generalizes across inputs (params/datatypes/wrappers)? Verified distributed-equals-local for all four family functions and for the -If, -ForEach (Array nested) and -ArgMax combinator wrappers. The predicate is whole-type, so a state nested in a container is compared by its announced binary encoding. Every column pair whose types already agree takes an early exit.
h Backward compatible? (maintainer-approved exception only) Yes. No new or changed setting, so no SettingsChangesHistory.cpp entry is owed; no serialization format, Native version or query-plan version change.
i Invariants and contracts preserved? Row count and chunk infos survive the conversion (detachColumns resets the count, so it is read first; chunk_infos is a separate member setColumns does not touch). The producer header is written under the exchange's existing mutex before the sink is constructed, so it happens-before any chunk becomes visible. A missing producer header throws LOGICAL_ERROR rather than failing open, which would recreate the very pair this removes. The zero-row scheduling tick and end-of-data paths are untouched.

Session id: cron:clickhouse-impl-slot-6:20260911-040700

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4b56432]


AI Review

Summary

PR #119401 restores aggregate-state variants across exchanges, casts, and query-plan deserialization. At head 4b564328c95885deca34eea83a60b490afa84c77, two uncovered boundaries remain: finalized inputs to HAVING can retain the unsafe layout mismatch, and implicit interpolation casts lose their target variant. Changes are required.

Missing context / blind spots
  • ⚠️ No current-head executable was available locally. Both findings follow concrete source-level type transitions; their SQL regression candidates in the inline comments have not been executed. Running those cases with serialization enabled and disabled would confirm the observed runtime behavior.
Findings

❌ Blocker — deserialize HAVING against its finalized header. TotalsHavingStep.cpp:220 passes the raw aggregate-state header to the DAG, although TotalsHavingTransform finalizes aggregate columns before executing it. For any(s), where s is a Window contingencyState, the raw outer any state cannot supply the variant of the DAG's finalized inner state. A cast of that value to its printed state type is rebuilt as an identity cast, allowing arrayReduce('contingencyMerge', ...) to read a Window pointer as Aggregation. This path is reachable through a complete IN subquery shipped by serialize_query_plan, independently of the distributed planner's rejection of WITH TOTALS. Derive the DAG input header by finalizing the aggregate columns when final is true; keep the raw header for aggregate descriptions.

⚠️ Major — restore interpolation output variants too. FillingStep.cpp:218 restores variants from DAG inputs, but cannot recover the Window target of an implicit cast added by the planner for an ordinary-state interpolation expression. Its type-name literal and any folded constant both decode as Aggregation. With the window and filling steps in one serialized stage, the strict output comparison at line 278 then rejects valid interpolation with INCORRECT_DATA. Convert variant-only mismatched outputs to the actual target types before validation, or preserve the internal cast's target variant; relabelling alone is unsafe.

Tests
  • ⚠️ Add a serialized IN subquery with GROUP BY p WITH TOTALS and HAVING arrayReduce('contingencyMerge', [CAST(any(s) AS AggregateFunction(contingency, UInt32, UInt32))]) >= 0, where s comes from contingencyState(b, c) OVER (PARTITION BY p). Compare serialize_query_plan = 1 and 0, forcing the outer table read through a remote replica.
  • ⚠️ Add ORDER BY v WITH FILL INTERPOLATE (s AS initializeAggregation('contingencyState', toUInt32(0), toUInt32(0))) over a Window state s. Compare a single-worker Cascades plan with local execution, keeping the window and filling steps in one stage.
Final Verdict

❌ Block. Correct the finalized-header and interpolation-output variant boundaries, and run focused regression cases for both.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 CrossTabCountsState::merge. The exchange now reconciles the representation with castColumn, the way NativeReader already does on the serialized leg.

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 543a33e6bdcb36a3031d90e6fd4a532c18be0e51 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "String" }, { "name…).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 702605e

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 03100_lwu_deletes_4_index trunk regression; the runner's own minimizer reproduced it 104/104 under the randomized pair min_bytes_for_wide_part=0 + patch_parts_version=v1. 55 unrelated pull requests and 13 true-master runs carry it over 30 days, and this PR touches no lightweight-update code #119400 (mine, open)

The 168 cancelled check-runs stamped 06:41:1xZ, and the Finish Workflow failure at 06:41:58Z, belong to
workflow run 34570979765: a duplicate dispatch created at 06:41:03Z and cancelled 56 s later. The
authoritative run is 34570986658 (Config Workflow 06:42:01Z, Finish Workflow success 11:55:50Z,
171 check-runs, 0 incomplete), whose only red is the row above. Mergeable Check agrees: Failed: Stateless tests (arm_binary, parallel).

Session id: cron:our-pr-ci-monitor:20260911-120034

groeneai and others added 3 commits September 25, 2026 12:15
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

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
  • StressHouse run: 2f0701c9-810d-49c0-8ff7-3107ec97c37c
  • MIRAI run: 8d3bb13e-cccf-4015-b813-05a4dd077108
  • PR check IDs:
    • clickbench_563042_1791559208
    • clickbench_563055_1791559208
    • clickbench_563061_1791559208
    • tpch_adapted_1_official_563067_1791559208
    • tpch_adapted_1_official_563098_1791559208
    • tpch_adapted_1_official_563112_1791559209

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 59969f2

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, 3/4) / test_memory_limit/test.py::test_multiple_queries not from this PR (which changes how a CrossTab window state crosses the in-memory exchange): the memory cgroup OOM-killed the server in the test's 4 GiB container (dmesg: anon-rss:4173136kB), so the final SELECT 1 got No route to host. The same kill hit true master on 2026-10-01; the open question on it is #117681 a fix task is created (its fix direction awaits the memory tracker owner's decision; fixing-PR link to follow on this PR)
Stateless tests (arm_asan_ubsan, azure, sequential) infra: all 1180 tests passed, then the job hit its 9000 s timeout (the job is allow_failure) #123849 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05316_secret_arguments_declared_by_engines not from this PR: the DatabaseReplicated double count seen on 132 PRs (0 2 instead of 0 1 for the CREATE DICTIONARY row; the password stays hidden). 22/22 reruns pass #124928 (external, merged 17:58Z). This run was dispatched before that merge, and the next master merge picks it up. I am not merging master now: the integration row stays red until its fix lands
Mergeable Check, PR praktika rollups of the two gating rows above (Failed: 2) a fix task is created (the integration row), #124928 (external, merged)

Session id: cron:our-pr-ci-monitor:20261009-190009

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_memory_limit/test.py::test_multiple_queries row of the ledger above: #126176 (external, open).

…mory-exchange-state-variant

# Conflicts:
#	docs/resources/develop-contribute/native-protocol/format.mdx
#	src/QueryPipeline/DistributedPlanExecutor.cpp
groeneai and others added 5 commits October 22, 2026 11:00
…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]>
groeneai and others added 4 commits October 25, 2026 20:26
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review of this update (the -Merge rebuilt inside one stage) by an independent model (engine: codex),
plus my own cold review of the resulting tree before reading the implementation notes, in each round.

Finding Verdict
❌ u1: a state whose argument holds a window state (e.g. groupArrayState over one) counts as variant-different, but CAST can neither relabel nor convert it AGREE, fixed in b607146: returned through the gather or spilled by a sort it failed with CANNOT_CONVERT_TYPE; CAST now relabels a state whose own variant matches and whose arguments differ only by the variant. Test section in 3839518
⚠️ u1: the node-id preservation for the join step has no test that inserts casts inside a join DAG AGREE: under Cascades the cast is inserted inside JoinStepLogical::deserialize, and resolving the nodes by position fails with CANNOT_PARSE_BOOL. Test section in 44255db
⚠️ u1: the spill sections do not assert in the test that the sort spilled Not changed: each spill section fails on master and without the NativeReader change, and spilled in all 51 randomized runs; a query_log check per section costs a log flush
⚠️ u1: the Cascades sections do not assert that the merge runs inside the deserialized stage Not changed: with Cascades the whole query, final aggregation included, runs in a deserialized stage, and with fallback off a non-distributable plan throws; both sections fail without the change

Round 2 (the two fixes above): no findings from either review.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The fuzzer's query with make_distributed_plan = 1, enable_cascades_optimizer = 1 segfaults in CrossTabCountsState::merge on every run on master and on the previous head; groupArrayState over a window state, returned through the gather or spilled by a sort, failed with CANNOT_CONVERT_TYPE on the previous head on every run.
b Root cause explained? Yes. The type encoding omits the state variant, so AggregatingStep::deserialize built -Merge for the aggregation layout and ran the plain merge over window states produced in the same stage; and CAST refused a state whose argument types differ only by the variant.
c Fix matches root cause? Yes. The deserialized step takes the variant from its input column, as WindowStep::deserialize already does; CAST relabels a state whose own variant matches and whose arguments differ only by the variant.
d Test intent preserved / new tests added? Yes. Five 05182 sections (a liveness row and four cases); existing sections and reference lines unchanged.
e Both directions demonstrated? Yes. The LIMIT BY, -MergeArray and nested-state sections fail on master or on the previous head; each case section fails without its change (the call site, the CAST relabel, or the join step's id-based node resolution); all match the local plan with the fix.
f Fix is general across code paths? Yes. The only steps that rebuild an aggregate from wire types are AggregatingStep (fixed), the merge-only steps and WindowStep (already header-derived); both cast sites of a nested state (exchange, NativeReader) go through the one CAST wrapper.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. All CrossTab functions; -Merge, -MergeIf, -MergeArray, -MergeState, -TupleMerge; groupArray and argMax over the state; no key, keys, ROLLUP, CUBE, external GROUP BY, spilled sort, join condition; 1 and 4 workers: all match the local plan.
h Backward compatible? (maintainer-approved exception only) Yes. No format change or setting.
i Invariants and contracts preserved? Yes. An aggregate's argument types equal its input columns' types again; a name that is not unique in the header keeps its decoded type; CAST relabels only identical encodings, and the outer state does not depend on the argument's variant.

Session id: cron:clickhouse-impl-slot-4:20261025-210800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat, could you review the aggregation part of this update? Under enable_cascades_optimizer = 1 a window state merged by -Merge in the same stage reached AggregatingStep::deserialize, which rebuilt the -Merge from the wire-decoded argument types (the encoding omits the state variant) and ran the aggregation-layout merge over window states; the deserialized step now takes the variant from its input column, as WindowStep::deserialize already does.

Comment thread src/Functions/FunctionsConversion.cpp Resolved
groeneai and others added 3 commits October 26, 2026 00:23
…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]>
groeneai and others added 2 commits October 26, 2026 03:05
…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);

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.

❌ 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);

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.

⚠️ Reconcile interpolation outputs with the actual target variants

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 nickitat 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.

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.

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed. Keeping the window layout inside WindowTransform removes the cause, while this PR converts the state at each place it escapes, and more of those keep turning up.

05182_distributed_plan_window_state_variant.sql here is plain SQL that runs each escape path I hit (sorted gather; -Merge, -Map, -Tuple, -MergeArray; CAST to Variant, Dynamic and the state type; lambdas; arrayJoin; external sort with spill; states nested in other states; ROLLUP/CUBE and joins in a Cascades stage) and checks each against the non-distributed or non-spilled run, so it can be reused to check your fix.

Should I close this PR now, or keep it open until yours is up?

@davenger

davenger commented Nov 2, 2026

Copy link
Copy Markdown
Member

@nickitat @groeneai I have a fix with the same idea in #128685 (draft): a function under -State in a window function always uses the ordinary layout, so a window-layout state never gets out of WindowTransform, and ColumnAggregateFunction throws a LOGICAL_ERROR if a column ever gets a function with the window layout. The test of this PR passes on it (after a change of its Variant subcolumn reads, because UNION ALL no longer makes a Variant), and so do the two HAVING/INTERPOLATE cases from the AI review above. -Merge in a window function keeps the window layout and the direct merge, so the speed of #93384 stays.

@nickitat

nickitat commented Nov 2, 2026

Copy link
Copy Markdown
Member

Ok, let's close this one then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants