Repository navigation
Support serialization of WindowStep for distributed query plans - #109802
Conversation
`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]>
059ef37 to
c2376ba
Compare
|
Workflow [PR], commit [5034c29] Summary: ✅
AI ReviewSummaryThis PR makes PR Metadata
Final VerdictStatus: ✅ Approve |
`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]>
…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]>
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]>
|
@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? |
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]>
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]>
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]>
…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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 115/128 (89.84%) · Uncovered code |
|
Hi @VighneshPath @davenger — while reviewing this PR I found the following:
Could you review the test PR and add the |
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
Window functions could not be used with
make_distributed_plan = 1becauseWindowStepdid not implement query plan serialization, so such queries wererejected before execution.
This implements
serialize/deserializeforWindowStep(window name,PARTITION BY,ORDER BY, the window frame, and the window functions) andregisters the step. Window functions also require a partition-aware full
SortingStepin front of them, soSortingStepserialization is extended tocarry
partition_by_description; the empty case stays byte-compatible with theprevious format.
Only non-partitioned windows (
OVER (ORDER BY ...), with noPARTITION BY)are distributed for now: a
PARTITION BYwindow's feeding sort cannot yetpreserve per-partition order across the exchange, so it is rejected with
SUPPORT_IS_DISABLEDinstead of silently distributing it.PARTITION BYsupport is a follow-up.
WindowStepserialization also requires all nodes to be on query planserialization version >= 4 (this PR bumps
DBMS_QUERY_PLAN_SERIALIZATION_VERSIONto 4); an older node fails closed instead of erroring on an unrecognized
Windowstep.Closes: #109308
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Support non-partitioned window functions (
OVER (ORDER BY ...)) in distributedquery plans (
make_distributed_plan). Previously any query with a windowfunction failed because
WindowStepcould not be serialized for remoteexecution; windows with
PARTITION BYare still rejected for now.Version info
26.8.1.615(included in26.8and later)