Skip to content

Support serialization of WindowStep for distributed query plans - #109802

Merged
davenger merged 12 commits into
ClickHouse:masterfrom
VighneshPath:serialize-window-step
Aug 1, 2026
Merged

davenger merged 12 commits into
ClickHouse:masterfrom
VighneshPath:serialize-window-step

Conversation

@VighneshPath

@VighneshPath VighneshPath commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Window functions could not be used with make_distributed_plan = 1 because
WindowStep did not implement query plan serialization, so such queries were
rejected before execution.

This implements serialize/deserialize for WindowStep (window name,
PARTITION BY, ORDER BY, the window frame, and the window functions) and
registers the step. Window functions also require a partition-aware full
SortingStep in front of them, so SortingStep serialization is extended to
carry partition_by_description; the empty case stays byte-compatible with the
previous format.

Only non-partitioned windows (OVER (ORDER BY ...), with no PARTITION BY)
are distributed for now: a PARTITION BY window's feeding sort cannot yet
preserve per-partition order across the exchange, so it is rejected with
SUPPORT_IS_DISABLED instead of silently distributing it. PARTITION BY
support is a follow-up.

WindowStep serialization also requires all nodes to be on query plan
serialization version >= 4 (this PR bumps DBMS_QUERY_PLAN_SERIALIZATION_VERSION
to 4); an older node fails closed instead of erroring on an unrecognized
Window step.

Closes: #109308

Changelog category (leave one):

  • Improvement

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

Support non-partitioned window functions (OVER (ORDER BY ...)) in distributed
query plans (make_distributed_plan). Previously any query with a window
function failed because WindowStep could not be serialized for remote
execution; windows with PARTITION BY are still rejected for now.

Version info

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

@CLAassistant

CLAassistant commented Jul 8, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

`WindowStep` did not implement query plan serialization, so any query
containing window functions failed under `make_distributed_plan = 1`.

Implement `serialize`/`deserialize` for `WindowStep`, covering the window
name, `PARTITION BY`, `ORDER BY`, the window frame, and the window functions,
and register the step in `QueryPlanStepRegistry`.

Window functions require a partition-aware full `SortingStep` in front of
them, so also extend `SortingStep` serialization to carry
`partition_by_description`. The empty case stays byte-compatible with the
previous format.

Remove `04310_distributed_unserializable_step_rejected`, which asserted that
window functions were rejected as unserializable, and add
`04506_distributed_plan_window_function` covering `PARTITION BY`, `ORDER BY`,
and a `ROWS` frame under `make_distributed_plan = 1`.

Closes: ClickHouse#109308

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@VighneshPath
VighneshPath force-pushed the serialize-window-step branch from 059ef37 to c2376ba Compare July 16, 2026 05:02
@davenger davenger self-assigned this Jul 23, 2026
@davenger davenger added the can be tested Allows running workflows for external contributors label Jul 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5034c29]

Summary: ✅


AI Review

Summary

This PR makes WindowStep serializable for distributed query plans, registers the step, hardens deserialization of window metadata and functions, and bumps query-plan serialization to version 4 with compatibility gates. I re-checked the current code against the earlier discussion and did not find any remaining blocker or major issue; the previously raised correctness and compatibility problems appear fixed.

PR Metadata

Changelog category and Changelog entry are both correct for the final code and specific enough for users. The only remaining metadata nit is that the long PR description still says SortingStep serialization was extended to carry partition_by_description, but the current diff reverted that part and still rejects PARTITION BY windows for now.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 23, 2026
Comment thread src/Processors/QueryPlan/WindowStep.cpp Resolved
`deserializeWindowFunctions` in `WindowStep::deserialize` rebuilt each
aggregate function via `AggregateFunctionFactory::get` without a state
variant, so it defaulted to `AggregateFunctionStateVariant::Aggregation`.
For a `WindowStep` that drops any registered `window_creator` and
reconstructs the GROUP BY implementation instead of the window-specific
one.

In practice this regressed the CrossTab window aggregates (`cramersV`,
`cramersVBiasCorrected`, `contingency`, `theilsU`): once the plan was
serialized under `make_distributed_plan = 1`, they ran with the
non-window state representation, a much slower path than the local,
non-serialized plan. Pass `AggregateFunctionStateVariant::Window` so the
deserialized functions match how the planner originally built them.

Extend `04506_distributed_plan_window_function` with a `theilsU` window
aggregate case under `make_distributed_plan = 1` to cover the state
variant selection. It reads from a `MergeTree` table because
`ReadFromSystemNumbers` is not serializable for remote execution.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Processors/QueryPlan/SortingStep.h Resolved
VighneshPath and others added 3 commits July 23, 2026 21:52
…dows

Allowing partition-aware `SortingStep` into `make_distributed_plan` exposed a
distributed-execution ordering bug. `SortingStep::fullSort` intentionally keeps
one sorted stream per partition when `partition_by_description` is non-empty and
the task fans out to more than one thread. `GatherSendStep` then collapsed those
streams with `pipeline.resize(1)`, and `ResizeProcessor` does not preserve order,
so the per-task data reached `GatherReceiveStep` unsorted. The order-preserving
merge on the receive side then merged already-unsorted input, and a query such as
`sum(v) OVER (PARTITION BY a ORDER BY v)` computed the window over the wrong row
sequence.

Give `GatherSendStep` the same `maintain_sort_description` the receive side
already has, and when it is set merge the incoming streams with
`MergingSortedTransform` instead of `resize`. Both produce the single stream the
exchange file requires, but the merge keeps the stream globally sorted, so the
receive-side merge sees sorted input and the window is computed correctly.

Add `04546_distributed_plan_window_partition_order`, which forces the partitioned
sort to fan out (`PARTITION BY` window, `max_threads > 1`, several parts) and
checks that the result under `make_distributed_plan = 1` matches the
non-distributed plan.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`04546_distributed_plan_window_partition_order` pins a precise set of settings to
force the distributed task's partitioned sort to fan out. Randomized settings make
`make_distributed_plan` reject the query (for example `max_rows_to_group_by` on the
checksum aggregation, or `optimize_read_in_order` / `extremes`), so the comparison
would not run and the test failed in CI. Add the `no-random-settings` tag.

Also fix a mislabeled argument comment on the `MergingSortedTransform` constructor
in `GatherSendStep` (the flag is `use_average_block_sizes`, not
`blocks_are_granules_size`); the value is unchanged.
The regression test aggregated (`sum(cityHash64(...))`) over the distributed
query to produce a checksum, but the stateless test profile sets
`max_rows_to_group_by`, and make_distributed_plan refuses to distribute an
aggregation while that limit is set, so the distributed query threw in CI and the
comparison never ran (the earlier failure was deterministic, not a randomization
effect).

Compare the window output rows directly (dist vs non-distributed) via md5sum
instead. A pure window query has no aggregation, so the limit no longer applies,
and the buggy path (the partitioned window sort fanning out into GatherSend) is
still exercised. Also set optimize_read_in_order = 0 so the partitioned sort is
materialized rather than skipped by a read-in-order optimization.

Verified with the clickhouse-test harness locally against a server carrying the
test profile's max_rows_to_group_by limit (5/5 runs green).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Processors/QueryPlan/WindowStep.cpp Resolved
VighneshPath and others added 2 commits July 24, 2026 08:30
serializeWindowFunctions re-read the parameter array from
aggregate_function->getParameters(), but some parametric aggregates
(groupArrayMovingSum, groupArrayMovingAvg, mannWhitneyUTest,
kolmogorovSmirnovTest) do not round-trip their parameters that way. As a result
deserializeWindowFunctions rebuilt the no-parameter variant on the worker, which
still has a matching result type, so make_distributed_plan silently returned a
different result. For example groupArrayMovingSum(3)(x) OVER (...) computed an
unbounded moving sum instead of a window of 3.

Serialize func.function_parameters, which the planner preserves, matching
serializeAggregateDescriptions. Add a make_distributed_plan regression for a
parameterized window aggregate.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…d) sorts

Distributing a PARTITION BY window requires a partition-aware SortingStep to be
serializable, but that exposes a correctness bug in the gather exchange:
SortingStep::fullSort keeps one sorted stream per partition (partition_by
non-empty and getNumThreads() > 1), GatherSendStep collapses them with
pipeline.resize(1) which does not preserve order, and GatherReceiveStep's merge
assumes each input stream is already sorted. So a PARTITION BY window computed the
result over the wrong row order once a task fanned out to multiple threads.

Revert the SortingStep serialization and GatherSendStep changes so partition-aware
sorts are once again not serializable; a PARTITION BY window under
make_distributed_plan now fails closed with SUPPORT_IS_DISABLED instead of
returning a wrong result. Windows whose sort is serializable (no PARTITION BY)
still distribute, which is what the WindowStep serde in this PR enables.

Rework 04506 to cover non-partitioned window distribution plus a fail-close
assertion for a PARTITION BY window, and drop 04546 (partitioned-order regression),
which no longer applies. Fixing the exchange to preserve partitioned order (so
PARTITION BY windows can distribute) is left to a follow-up in the exchange layer.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@VighneshPath

Copy link
Copy Markdown
Contributor Author

@davenger — PARTITION BY windows can't distribute safely: the partitioned sort fans out and GatherSendStep's resize(1) drops row order before GatherReceiveStep's merge (reproduced wrong results). I've gated them off (fail-close) for now.

The fix is to make GatherSend merge instead of resize(1) — but that changes the GatherSend payload, so it needs a DBMS_QUERY_PLAN_SERIALIZATION_VERSION bump. Should we do that in this PR, or as a follow-up in the exchange layer?

Comment thread src/Processors/QueryPlan/WindowStep.cpp Resolved
The previous commit reverted SortingStep to a stale local master, which would
have made the PR delete unrelated newer code on master (SortingStep::clone, the
SortingStage enum, describePipeline/getStepGroups, and the improved virtual-row
handling in RemoveVirtualRowTransform). Restore SortingStep to the branch's fork
point so the PR leaves it net-unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Processors/QueryPlan/WindowStep.cpp Resolved
TCPHandler::receiveQueryPlan accepts client-supplied query plans, so
deserializeWindowFunctions must not trust the serialized window-function
signature:

- It rebuilt argument types with bare decodeDataType, bypassing the
  input_format_binary_max_type_complexity guard the other deserializers apply.
- It trusted the serialized argument types and arity. WindowTransform sizes its
  argument workspace from argument_names and the aggregate reads those columns by
  position and casts them to its argument types, so a forged arity or a type that
  disagrees with the real input column could cause an out-of-bounds read or an
  invalid cast (e.g. avgWeighted advertising two arguments with one name, or a
  String column cast to a numeric ColumnVector).

Stop serializing argument types and derive them from the input header columns on
deserialize instead: the types then always match the columns WindowTransform
feeds, no client-supplied type is decoded (so the complexity guard is moot), and
the aggregate is rebuilt exactly as the planner builds it. A window function
referencing a column absent from the input header is rejected.

Also reject out-of-range window-frame enum values instead of casting an arbitrary
byte into the enum.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Processors/QueryPlan/WindowStep.h Resolved
@davenger

Copy link
Copy Markdown
Member

@davenger — PARTITION BY windows can't distribute safely: the partitioned sort fans out and GatherSendStep's resize(1) drops row order before GatherReceiveStep's merge (reproduced wrong results). I've gated them off (fail-close) for now.

The fix is to make GatherSend merge instead of resize(1) — but that changes the GatherSend payload, so it needs a DBMS_QUERY_PLAN_SERIALIZATION_VERSION bump. Should we do that in this PR, or as a follow-up in the exchange layer?

Let's do exchange-related changes in a follow-up

An older worker never registers a "Window" step in `QueryPlanStepRegistry`
(`WindowStep` support is new), so it would throw `UNKNOWN_IDENTIFIER` on the
step name rather than parsing it. Bump `DBMS_QUERY_PLAN_SERIALIZATION_VERSION`
to 4 and reject serializing/deserializing a `WindowStep` below that version
with a clear `SUPPORT_IS_DISABLED` error instead, matching the existing
bucketed-`ReadFromMergeTree` and parallel-replicas version gates.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Comment thread src/Core/ProtocolDefines.h Resolved
…ION_VERSION

Bumping the latter to 4 left the gate at a stale 3, so a mixed-version cluster
would admit a v3 replica then send it the v4-cached blob it can't parse.
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 115/128 (89.84%) · Uncovered code

Full report · Diff report

@davenger
davenger added this pull request to the merge queue Aug 1, 2026
Merged via the queue into ClickHouse:master with commit 7a4e895 Aug 1, 2026
179 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @VighneshPath @davenger — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 2, 2026
VighneshPath added a commit to VighneshPath/ClickHouse that referenced this pull request Aug 10, 2026
Follow-up to ClickHouse#109802 (window functions without PARTITION BY). A PARTITION
BY window's feeding sort carries partition_by_description, and
SortingStep::isSerializable() returned false for it, so make_distributed_plan
rejected such windows outright with SUPPORT_IS_DISABLED.

This teaches the wire format (bumped to version 6, with per-capability
gating constants) to carry SortingStep::Type::Full with a non-empty
partition_by_description, so the window's feeding sort can be shipped to
a worker instead of being rejected. GatherSendStep now merge-sorts
multiple order-preserving input streams instead of an unconditional
resize(1): scatterByPartitionIfNeeded deliberately leaves several
per-partition sorted streams un-merged whenever a worker has more than
one thread, and without this fix those streams would be interleaved out
of order before being sent, so a receiving GatherReceiveStep - which
declares the exchange sorted - would silently merge already-unsorted
data (this exact bug was reproduced with wrong results during the ClickHouse#109802
review).

Both new fields are version-gated below the version that could
misinterpret them, matching the existing WindowStep pattern: an older
peer fails closed with SUPPORT_IS_DISABLED rather than misparsing the
stream, and writing an empty partition_by_description to a peer below
that version produces byte-identical output to today (no extra bytes are
written at all below the gate, so an old peer's deserializer, which never
expected a trailing field, is unaffected).

With this alone (no distribution rewrite), a PARTITION BY window under
make_distributed_plan now runs correctly - gathered onto one node,
instead of being rejected. Distributing the computation across workers
in parallel is a separate, more involved piece of work; I'm not taking
that up further (see the linked issue for details).

Related: ClickHouse#109308
Related: ClickHouse#109802
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 pr-improvement Pull request with some product improvements 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.

Implement serde for WindowStep and support it for makeDistributed

5 participants