Skip to content

Do not reject a deserialized plan header over the aggregate state variant - #114020

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-window-step-aggregate-state-variant-header
Aug 15, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-window-step-aggregate-state-variant-header

Conversation

@groeneai

@groeneai groeneai commented Aug 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #113989

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Fixes a logical error when a distributed query plan contains a window function producing an aggregate function state, for example theilsUState(a, b) OVER (ORDER BY a) with make_distributed_plan = 1. Affects the cramersV, cramersVBiasCorrected, theilsU and contingency families.

Description

SELECT theilsUState(a, b) OVER (ORDER BY a) FROM t SETTINGS make_distributed_plan = 1 aborts the
worker in debug and sanitizer builds, printing two identical types as the mismatch.

The differing field is AggregateFunctionStateVariant, which no type name prints.
encodeAggregateFunction omits it and decodeAggregateFunction calls the factory without one, so it
defaults to Aggregation. The initiator's Window header therefore round-trips back as
Aggregation, and strictEquals, which compares the variant first, rejects the pair. That rules out
the version hypothesis in #113989: identical printed names exclude a version difference, since the
name includes it.

I relaxed this one comparison rather than put the variant on the wire: that encoding is not
plan-private (Dynamic and JSON type tags share it, so its bytes reach stored data), and
NativeReader already tolerates the same variant-only difference for the same reason. The check now
accepts a header pair encoding to identical bytes, i.e. a difference the serializer cannot express.
The variant is the only field equals compares that the encoding omits, so nothing else newly
passes. Comparing bytes rather than calling equalsIgnoringVariant also covers a state nested in
Array(...) from -ForEach, which that top-level method cannot see.

State layouts cannot be confused: ColumnAggregateFunction carries its own function pointer and
consumers finalize through that, so the header type is validation metadata, not the interpreter. The
assertion's other callers stay strict.

Out of scope: the lost variant also reaches a lambda capture in a deserialized ActionsDAG, so
arrayMap over a -ForEach window state still aborts, as on master. Relaxing that guard would
weaken a check over a capture path shared by every higher-order function.

No changelog entry because no stable release can reach this: WindowStep became serializable only
in #109802 (2026-08-01), absent from 26.7 and earlier. Seen on 3 unrelated pull requests, none on
master.

Version info

  • Merged into: 26.8.1.1452 (included in 26.8 and later)

…iant

A distributed query plan containing a Window step over an aggregate function
state column aborted the worker with a LOGICAL_ERROR whose two printed types
were byte-identical:

  Block structure mismatch in deserialization of query plan Window step stream:
  different types:
  theilsUState(...) OVER (...) AggregateFunction(theilsU, UInt32, UInt32) ...
  theilsUState(...) OVER (...) AggregateFunction(theilsU, UInt32, UInt32) ...

The differing field is AggregateFunctionStateVariant, which getNameImpl never
prints. encodeAggregateFunction does not carry it either, and
decodeAggregateFunction calls the factory with no variant, so it defaults to
Aggregation. The initiator's Window variant is therefore decoded on the worker
as Aggregation, while the rebuilt WindowStep's own output header legitimately
carries Window, and strictEquals compares the variant first. The version IS
printed and IS encoded, so identical printed types rule a version difference
out.

Accept a header pair only when both headers encode to identical bytes, i.e.
when the difference cannot have come off the wire at all. Every difference the
plan serializer can express, including the state version, is still rejected
with the unchanged message. The encode runs only after the strict check has
already failed, so it is off the hot path. No format change, so no plan
serialization version bump and no mixed-version concerns: a plan that aborted
before now succeeds, and a new initiator talking to an old worker behaves
exactly as today.

Comparing encoded bytes rather than calling the existing
equalsIgnoringVariant reuses the encoder's own recursion, so a state nested in
Array(...) from -ForEach is covered too; equalsIgnoringVariant is a method on
DataTypeAggregateFunction and can only see a top-level state. NativeReader
already tolerates the same variant-only difference at its own header check,
for the same reason.

The two variants are required to share their serialization format
(IAggregateFunction.h) and do: a Window-produced theilsU state and an
Aggregation-produced one are byte-identical and each finalizes to the same
value through the other's type. The relaxation cannot confuse state layouts
because ColumnAggregateFunction carries its own aggregate function pointer and
consumers finalize through that, so the header type is validation metadata
rather than the interpreter of the bytes.

The same lost variant also reaches a lambda capture inside a deserialized
ActionsDAG, which compares with the same variant-sensitive equals. That site
is left unchanged, so a higher-order function capturing a -ForEach window
state still aborts, exactly as it does on master today, where the header check
rejects it first. Relaxing it would weaken a guard over a real execution-time
capture on a path shared by every higher-order function.
The deserialized header check only runs once a plan splits into more than one
stage: QueryPlan::convertToDistributed collapses a one-stage plan back to local
execution and force-disables make_distributed_plan, so a query that stays
single-stage would pass without ever reaching the check. Nothing in the test
pinned the split, and re-running the file with make_distributed_plan = 0
reproduced the reference byte-for-byte, so a later planner change could make
any of these shapes single-stage and the arm would keep passing while covering
nothing.

Assert the split for the two structurally distinct header shapes, a plain state
and a state nested in Array(...) from -ForEach, with the oracle
04628_read_nothing_step_serializable already uses at this site. The row is
absent unless an exchange was planted, so dropping make_distributed_plan now
makes the test fail on exactly those two rows instead of silently covering
nothing. The oracles do not aggregate: an aggregating query over EXPLAIN is
itself distributed and would make the oracle self-satisfying.
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Before opening this PR I ran an independent cold code review plus a second-model review of the
diff, and adjudicated every finding against the recorded evidence. Verdicts below.

❌ Fixed in this PR

Test could go vacuous without failing (major). All 7 assertions in the new test were verified
to abort at the deserialized-header check on a pre-fix binary, so the test was live. But that
liveness is a property of the planner, not of the test: a one-stage plan is executed locally with
make_distributed_plan force-disabled, and re-running the file with make_distributed_plan = 0
reproduced the committed .reference byte-for-byte. A later planner change that made these shapes
single-stage would leave every assertion passing while covering nothing. Fixed by adding two
non-aggregating EXPLAIN PIPELINE oracles asserting ReadFromDistributedPlanSource, one for a
plain state and one for a state nested in Array(...) from -ForEach, following
04628_read_nothing_step_serializable. Verified discriminating: with make_distributed_plan = 0
the run now fails on the missing oracle rows.

Changelog category (major, found in my own review). The draft said
Bug Fix (user-visible misbehavior in an official stable release). No stable release can reach
this path: WindowStep became serializable in #109802 (merged 2026-08-01), and 26.7 was cut
2026-07-22. Measured on live refs, WindowStep.cpp contains serializeWindowFunctions 5 times on
master and 0 times on each of 26.7, 26.6, 26.5, 26.3 and 25.8. Changed to
Not for changelog, keeping a user-readable entry.

A claim of mine was wrong, and the second model caught it (nit). A previous round of this
review asserted that a differing aggregate state version would still be rejected, and that sentence
reached the description. It is false: DataTypeAggregateFunction::equals compares
function->getNormalizedStateType() on both sides, and getNormalizedStateType
(IAggregateFunction.cpp:20-27) rebuilds the type without the explicit version, so strictEquals
never sees one. Version-only differences already pass the strict check on master, before this
change. This does not widen the new fallback: the version IS encoded
(DataTypesBinaryEncoding.cpp:485), so differing versions produce differing bytes and the byte
comparison cannot admit them. The set of pairs this PR newly accepts is still exactly the
variant-only ones. The description is corrected; the first commit's message keeps the same
overstatement in one sentence.

⚠️ Reviewed and disagreed, with evidence

"Byte equality is broader than a variant-only relaxation." True in form, equivalent in effect on
the current tree. Walking getBinaryTypeIndex and encodeDataTypeImpl against every
plan-reachable equals, the state variant is the only field that is compared but not encoded. The
one other lossy case, DateTime omitting an implicit timezone, never reaches the new branch
because DataTypeDateTime::equals already accepts all timezones. Scale, enum values, decimal
precision, QBit stride and Dynamic max_types are all encoded and all compared.

"The new helper can throw where the old code could not." encodeDataType throws for a type
with no binary encoding, but the expected header came off the wire, so it was decodable and is
therefore encodable; and the helper runs only after the strict check has already failed, i.e. on a
path that was about to throw anyway. Recursion is bounded by checkStackSize.

Float formatting in the reference. The window path returns a literal 0.0 under a <= guard
with a negative clamp, so it cannot print -0; NaN is quiet with a clear sign bit, so it prints
nan. The tightest of the 11 finite values sits 0.04 of a 1e-6 tick from a rounding tie.

💡 Noted, not blocking

The test asserts values, so it cannot distinguish "the relaxation was applied" from "the check was
removed"; a negative arm would need a forged plan stream, which a stateless .sql test cannot do.
The strict path keeps its own coverage through the assertion's six other callers and the
fail-closed SUPPORT_IS_DISABLED assertion in 04506.

The memory-safety argument was re-derived independently rather than taken from the diff comments:
the two state structs really are different types, but nothing reinterprets one as the other, since
ColumnAggregateFunction carries its own function pointer and consumers finalize through it.

Merge-order note for #111824 (framed outline format), which is open and touches this line: it adds a
second deserialization loop with its own assertCompatibleHeader call rather than replacing this
one, so its head currently has two call sites where master has one. If it merges after this PR,
the new loop will need the same two-tier check or the abort returns on that path. Flagging the
interaction only; that PR is not mine to change.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand, not a rate: 4-row MergeTree table, SELECT finalizeAggregation(theilsUState(n, n) OVER (ORDER BY n)) FROM t SETTINGS make_distributed_plan = 1, enable_parallel_replicas = 0, distributed_plan_execute_locally = 1. No fuzzer, no view(). Oracle is the server log line, since the client only sees Code: 32 ATTEMPT_TO_READ_AFTER_EOF.
b Root cause explained? encodeAggregateFunction writes name, parameters and argument types but not the state variant, and decodeAggregateFunction calls the factory with no variant, so it defaults to Aggregation. The initiator's header carries Window, so the expected header round-trips back as Aggregation, and strictEquals compares the variant first. Both sides print identically because no type name includes the variant. The version hypothesis in #113989 is ruled out: the name does include a non-zero version.
c Fix matches root cause? Yes, at the check site: accept only header pairs that encode to identical bytes, i.e. differences the plan serializer cannot express. Not a band-aid, since the variant is provably not on the wire, so the comparison was reading a field the serialized side could never populate. The state variant is the only field equals compares that the encoding omits, so the relaxation admits nothing else.
d Test intent preserved / new tests added? No existing test weakened or removed. One new stateless test, 04734_distributed_plan_window_aggregate_state_variant, with 7 assertions; verified to redden on pristine master.
e Both directions demonstrated? Yes, on Build-ID-verified binaries: pre-fix the server log gains the mismatch line, post-fix the query returns its rows and the log gains none. 17 aborting arms go to 0. 100 runs of the new test (50 randomized, 50 not) pass.
f Fix is general across code paths? The change sits at the single generic per-step header check, so it covers every step whose rebuilt header can carry a window-variant state, not just WindowStep; verified with two-step and three-step subquery arms. The other 6 callers of the assertion stay strict on purpose, since Port.cpp guards a real pipeline connect. One sibling consumer (a lambda capture in a deserialized ActionsDAG) is deliberately out of scope and disclosed in the description.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured on all four CrossTab family members, on the -If, -ArgMax, -Array, -ForEach, -Resample and -OrNull combinators, and on Nullable and LowCardinality argument types: every one goes from abort to pass. Wrapper recursion is inherited from the encoder, which already handles Nullable, LowCardinality, Array, Map, Tuple and Nested; that is why encoded-byte equality was chosen over the top-level-only equalsIgnoringVariant.
h Backward compatible? (maintainer-approved exception only) Yes, and no exception needed. No format change, so DBMS_QUERY_PLAN_SERIALIZATION_VERSION is untouched, no SettingsChangesHistory.cpp entry and no new setting. Strictly more permissive: a plan that aborted now succeeds, and a new initiator talking to an old worker behaves exactly as before.
i Invariants and contracts preserved? Yes. The header DataType is validation metadata, not the interpreter: ColumnAggregateFunction carries its own AggregateFunctionPtr and consumers finalize through it, and on the worker that column comes from WindowTransform built with the correct Window function, so a variant-only header difference cannot cause a layout confusion. The two variants are required to share their serialization format (IAggregateFunction.h) and do, proven by a byte-level round trip: identical hex(), and a Window-produced state finalized through the Aggregation type yields the same non-degenerate value, with a differing negative control. The encode runs only after the strict check has failed, so the hot path is unchanged.

Session id: cron:clickhouse-impl-slot-41:20260809-032400

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @yariks5s, could you review this? The plan header encoding does not carry AggregateFunctionStateVariant, so a Window-variant aggregate state decodes back as Aggregation and the per-step header check rejects two types that print identically. The check now also accepts a pair whose serialized bytes are equal, which is the only difference the serializer cannot express.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2340812]

Summary: ✅


AI Review

Summary

This PR relaxes query-plan header validation during deserialization when the reconstructed header serializes to the same bytes as the header that came off the wire, which fixes distributed Window plans carrying CrossTab aggregate states whose AggregateFunctionStateVariant is not encoded. I reviewed the current diff, the linked issue, the surrounding QueryPlan::deserialize and type-encoding code, the prior PR discussion, and the new regression test, and I did not find a correctness, compatibility, or test-coverage problem in the patch as it stands.

Final Verdict

✅ No blocking findings.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 10/13 (76.92%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2340812ec with master 8cb46d93b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.64 MiB 687.62 MiB -3.02 MiB (-0.44%)

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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2340812

CI is fully finished on this head and every check that ran is green: 154 success, 21 skipped, 0 failure. The praktika report's top-level status is OK with 0 dropped jobs, so the skips are genuine config-level skips ("not affected by the changed files", "no build-affecting changes", "reused from cache"), not a dropped matrix.

Check / test Reason Owner / fixing PR
none no failures on this head -
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260811-170000

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks weird to me. It's hard to understand why did this complication arise.
Worth asking @davenger. In the meantime, it is good to merge.

@alexey-milovidov alexey-milovidov self-assigned this Aug 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 15, 2026
Merged via the queue into ClickHouse:master with commit f4b24b8 Aug 15, 2026
179 checks passed
@groeneai

Copy link
Copy Markdown
Collaborator Author

The awkwardness is that the plan header encoding is not plan-private.

encodeAggregateFunction writes the function name, the parameters and the argument types, and no
state variant (DataTypesBinaryEncoding.cpp:272); the decode side rebuilds the type through the
factory (:777), which always yields the Aggregation variant. But DataTypeAggregateFunction::equals
goes to strictEquals, which compares the variant first (DataTypeAggregateFunction.cpp:182). So a
Window state header cannot survive its own round-trip, and because the printed name omits the
variant, the assertion prints two identical types.

Putting the variant on the wire is the obvious fix, but those bytes are shared with stored data:
Dynamic and JSON type tags use the same encoding. equalsIgnoringVariant on its own does not
reach a state nested in Array(...) from -ForEach, which is why the check compares bytes.
NativeReader already tolerates the same variant-only difference, for the same reason, when an
external sort spills blocks (NativeReader.cpp:266).

@davenger, one forward-looking question, since #111824 touches this line: at f3675425 it has two
assertCompatibleHeader call sites (:492 and :761) where master now has one two-tier check. Does
the framed format intend to carry the variant, which would remove the need for the check entirely, or
should both loops take the same check?

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

Labels

can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: Block structure mismatch in deserialization of query plan Window step for AggregateFunction state (distributed plan)

4 participants