Skip to content

Gate the -Merge aggregate state version on a protocol revision - #123070

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-merge-combinator-state-version-122935
Oct 10, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-merge-combinator-state-version-122935

Conversation

@groeneai

@groeneai groeneai commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122935
Related: #112052
Related: #122853

Changelog category (leave one):

  • Improvement

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

Keep exchanging -Merge aggregate states with servers of older releases working: the state version of a -Merge function follows the state version of the function it merges only for peers that announce the new protocol revision 54494.

Description

The original bug of #122935 (-Merge states always sent at version 0, and ColumnBLOB::toBLOB writing the local type's version) is already fixed on master by the uniq state version 1 change, which forwards getVersionFromRevision in AggregateFunctionMerge and derives the version in ColumnBLOB::toBLOB. That forward is not gated by a revision: 26.8 and 26.9 send -Merge states at version 0 without announcing it, so a master server cannot read them (UNKNOWN_CODEC) and they cannot read the states it sends.

This PR gates the forward on the new revision 54494 (DBMS_MIN_REVISION_WITH_MERGE_COMBINATOR_STATE_VERSION, after 54493 of the uniq state version 1), so -Merge states to and from older peers are unchanged, and shares the version derivation between NativeWriter::write and ColumnBLOB::toBLOB in NativeWriter::setAggregateFunctionStateVersions. The new test covers quantileDeterministicMerge, sumMapMerge and maxMapMerge over remote(), also with parallel blocks marshalling; it passes on master as well, so the bugfix validation does not apply.


Workflow [PR]
Sync PR [sync-upstream/pr/123070]

Version info

  • Merged into: 26.10.1.2073-master (included in 26.10 and later)

groeneai and others added 3 commits September 30, 2026 11:39
…over distributed queries

`medianDeterministicMerge(state)` over `remote()`, a `Distributed` table or
parallel replicas returned a split-dependent result (486416 instead of
492708 for the query of ClickHouse#122935), and a `GROUP BY` of `medianDeterministic`
over `remote()` failed with `Skip degree in quantileDeterministic state is
136, which exceeds the maximum value of 31`. Both are writes of a state at a
version other than the one announced for the peer:

- `AggregateFunctionMerge` forwarded `isVersioned` and `getDefaultVersion`
  but not `getVersionFromRevision`, so `NativeWriter` derived version 0 for
  every `-Merge` intermediate state and the reservoir's skip degree was
  dropped. The forward is gated on the new revision 54493: 26.8 and 26.9
  (revision 54492) send `-Merge` states at version 0 without announcing a
  version, and an ungated forward makes a new initiator read one byte too
  many per state from them (measured against 26.9.6.6: `UNKNOWN_CODEC`).
- `ColumnBLOB::toBLOB` (parallel block marshalling) serialized with the
  local type's version while `NativeWriter::write` announced the
  revision-derived one. Both now go through
  `NativeWriter::setAggregateFunctionStateVersions`.

A newly declared `-Merge`-typed column now gets the current state version
pinned at `CREATE`, like a column of the function itself, so it keeps the
skip degree in storage; existing tables keep version 0.

Closes ClickHouse#122935.
CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=122853&sha=ec896d3cdcb1f79f80021244714eebe4ff779fc9&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
PR: ClickHouse#122853

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Arm E covers the other versioned nested functions under `-Merge`. Without
the forward, a shard sends a `sumMapMerge` partial state at version 0, which
writes each sum with the `UInt8` value type (600 becomes 88, so the result
is `([1],[288])` instead of `([1],[800])`), and a marshalled `GROUP BY`
block of `sumMapMerge` or `maxMapMerge` states is written at version 1 but
read as version 0. Measured the same on master and on 26.9.6.6.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the call-site comment in ColumnBLOB::toBLOB (the helper's declaration documents it) and cut the revision constant's comment to one line.

Co-Authored-By: Claude Opus 5.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 30, 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; 4 findings over 2 rounds) plus my own
cold review of each round (8 findings). One fix round (arm E of the test).

# Sev Finding Verdict Evidence / action
1 ⚠️ The -Merge forward also changes the wire version of sumMap/maxMap/groupBitmapAnd/Or -Merge states, which the PR text and test did not cover AGREE, fixed @ 29bd93e measured with UInt8 values: master and 26.9.6.6 give ([1],[288]) for sumMapMerge over remote() (truth ([1],[800])) and misread the marshalled GROUP BY block; arm E pins it, the description names it
2 ⚠️ Arms B/C do not prove that parallel block marshalling handled the block DISAGREE deleting the ColumnBLOB::toBLOB line makes arm B fail with Code: 36 (skip degree 207) and arm C with Code: 36 (136) at both prefer_localhost_replica values; the test pins enable_parallel_blocks_marshalling = 1 and single-level aggregation, the only randomized settings that bypass marshalling
3 ⚠️ Mixed-version compatibility of revision 54493 is not shown by the committed test DISAGREE a stateless test runs one server version; measured against the official 26.9.6.6 binary in both directions (new initiator with a 26.9 shard, 26.9 initiator with new shards, with and without GROUP BY): correct values, no error; without the gate the new initiator fails with UNKNOWN_CODEC
4 💡 "every master run" of the ParallelReplicas lane was overstated AGREE, fixed in the description CIDB, 30 days: 263 of 1317 master runs, each hidden by "Failed 0 out of 3 reruns"
5 💡 Say what the -OrNull/-OrDefault residual means AGREE, fixed in the description medianDeterministicOrNull over remote() stays split-dependent (506014 on master and with this PR)
6 💡 "Older peers keep today's behaviour" is true for -Merge states only AGREE, fixed in the description the marshalling change also fixes what a new shard sends a 26.9 initiator
7 💡 The description said both sites write a version other than the announced one; for -Merge the announced version itself was wrong AGREE, fixed in the description only the marshalling path wrote a different version than it announced
8 💡 groupBitmapXorMerge is not named next to groupBitmapAndMerge/OrMerge noted, no change same AggregateFunctionBitmapL2 implementation, fixed by the same line; the description names only the measured functions
9 💡 The test header describes only quantileDeterministic states noted, no change arm E carries its own comment
10 💡 A *WithNamesAndTypes import from an old unpinned -Merge-typed column into a new pinned one is refused by the type-name check noted, no change same class as the plain quantileDeterministic columns since #112052

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

Session id: cron:clickhouse-review-slot-10:20260930-130025

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: the new test through clickhouse client --multiquery fails on every run on master (issue query 486416 instead of 492708; plain GROUP BY over remote() Code: 36).
b Root cause explained? AggregateFunctionMerge does not forward getVersionFromRevision, so -Merge states go out at version 0 without the skip degree; ColumnBLOB::toBLOB serialized with the local type's version while NativeWriter announced the revision-derived one.
c Fix matches root cause? Yes: both version decisions are fixed where they are made; nothing is guarded on the reader side.
d Test intent preserved / new tests added? New 05296_quantile_deterministic_merge_over_network, one arm per mechanism (issue query, -Merge and plain function in marshalled blocks, pinned -Merge column, sumMapMerge/maxMapMerge of UInt8 states). Existing tests unchanged.
e Both directions demonstrated? Yes: master fails in every arm, the fix passes; deleting the forward reddens arms A, B, D and E, deleting the toBLOB line reddens B and C.
f Fix is general across code paths? Merge and OrFill are the only isVersioned overriders without the forward; wrappers over -Merge (-MergeState, -MergeIf, -MergeArray) are fixed transitively; OrFill is left unchanged on purpose. The version derivation is one helper used by both writers.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked quantilesDeterministic with parameters, sumMap/maxMap with UInt8 values, GROUP BY and no key, 1-row and multi-row blocks, prefer_localhost_replica 0/1, parallel replicas with parallel_replicas_local_plan 0/1, 50 randomized runs.
h Backward compatible? (maintainer-approved exception only) Yes: gated on the new revision 54493, so -Merge states to and from 26.8/26.9 peers keep today's behaviour (measured against the official 26.9.6.6 binary); existing tables keep version 0.
i Invariants and contracts preserved? The payload is written at the version announced for the peer on both write paths. Types are replaced, never mutated, and toBLOB works on its by-value copy, so shared header types are untouched.

Session id: cron:clickhouse-impl-slot-5:20260930-102600

@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e942536]

Summary: ✅


AI Review

Summary

This PR gates -Merge aggregate-state versioning on protocol revision 54494, routes ColumnBLOB::toBLOB through the same aggregate-version rewrite as NativeWriter, updates the native-protocol docs, and adds a solid stateless repro covering both quantileDeterministic and -Map states. The wire-path fix itself looks coherent, but one previously reported performance-model issue still remains unresolved in the current code.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/RuntimeDataflowStatistics.cpp:118] [dismissed by author -- https://github.com/Gate the -Merge aggregate state version on a protocol revision #123070#discussion_r4145720256] estimateCompressedColumnSize still samples aggregate-state columns through NativeWriter::getSerializationAndColumn / writeData without first applying NativeWriter::setAggregateFunctionStateVersions, so the runtime dataflow cache keeps modeling the pre-gate payload instead of the bytes the real wire now uses. This is not just the quantileDeterministic one-byte skip_degree delta from the original thread: for -Map states the serialized width changes by version (src/AggregateFunctions/AggregateFunctionSumMap.cpp:294), so sumMapMerge / maxMapMerge can materially under-estimate replica output bytes and skew the parallel-replicas cost model on grouped distributed aggregation queries.
    Suggested fix: run the same aggregate-version rewrite that NativeWriter::write now uses before sampling these columns (and ideally in the sibling aggregate-state estimator too), so both statistics paths measure the actual same-version wire layout rather than the stored/default one.
Final Verdict

⚠️ One prior major remains unresolved; I would keep the review open until the runtime-dataflow estimator mismatch is either fixed or explicitly accepted as a deliberate tradeoff.

LLVM Coverage Report

Measured on commit e942536.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 14/15 (93.33%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 30, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 30, 2026
static std::tuple<SerializationPtr, SerializationInfoPtr, ColumnPtr> getSerializationAndColumn(UInt64 client_revision, const ColumnWithTypeAndName & column);

/// Sets the state versions of the aggregate functions in `type` to the ones announced to a peer at `client_revision`.
static void setAggregateFunctionStateVersions(DataTypePtr & type, UInt64 client_revision);

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.

RuntimeDataflowStatisticsCacheUpdater::recordAggregationStateColumnSizes feeds the non-key aggregate-state columns into estimateCompressedColumnSize, and that helper still serializes them via the raw getSerializationAndColumn / writeData pair in src/Processors/QueryPlan/Optimizations/RuntimeDataflowStatistics.cpp:118-134. So Auto-PR will keep modeling the pre-54493 payload for exactly the -Merge / quantileDeterministic states this PR fixes on the real wire. That can underestimate replica output bytes and skew the parallel-replicas cost model on grouped/distributed aggregation queries.

Can we thread setAggregateFunctionStateVersions through that path as well, or move the version adjustment into the lower-level serialization API that these estimators use?

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.

Not changing this. estimateCompressedColumnSize only samples at most 8192 rows to model a compressed size for the cost model, and the state version only changes a few bytes per state (one UInt8 skip_degree for quantileDeterministic), so the estimate is not meaningfully affected. It also serializes at DBMS_TCP_PROTOCOL_VERSION with the type as stored, not the type announced to a particular peer, so there is no peer revision to derive a version from there.

@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit e94253609f69a547419572296303cc00279db693 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

…r-state-version-122935

Renumber the `-Merge` state version revision to 54494 after `uniq` state version 1 (54493), and unify the `AggregateFunctionMerge::getVersionFromRevision` override.
@fm4v fm4v changed the title Fix -Merge aggregate states and grouped quantileDeterministic over distributed queries Gate the -Merge aggregate state version on a protocol revision Oct 8, 2026
@fm4v

fm4v commented Oct 8, 2026

Copy link
Copy Markdown
Member

CI (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123070&sha=e94253609f69a547419572296303cc00279db693&name_0=PR): every job passed except Finish Workflow / new_tests_check.py, which requires bugfix validation for the "Bug Fix" category. The new test passes on the master binary, because master already forwards getVersionFromRevision in AggregateFunctionMerge (ungated) and derives the version in ColumnBLOB::toBLOB via the uniq state version 1 change. After merging master this PR is only the revision gate (54494) for older peers, so I changed the changelog category to Improvement and rewrote the description.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 8, 2026
| Aggregate-function versioning | `DBMS_MIN_REVISION_WITH_AGGREGATE_FUNCTIONS_VERSIONING` | `54452` | `AggregateFunction` state is written without an embedded version. |
| `skip_degree` in `quantileDeterministic` state | `DBMS_MIN_REVISION_WITH_QUANTILE_DETERMINISTIC_SKIP_DEGREE` | `54491` | `AggregateFunction(quantileDeterministic, ...)` states (and the `quantiles`/`median` spellings of the same function) are written at state version `0`, without the trailing `UInt8 skip_degree`. See the note under [type aliases](#type-aliases). |
| 64-bit hash sample in `uniq` state | `DBMS_MIN_REVISION_WITH_UNIQ_STATE_VERSION_1` | `54493` | `AggregateFunction(uniq, ...)` states are written at state version `0`: no leading flags byte and no trailing sample of 64-bit hashes. See the note under [type aliases](#type-aliases). |
| Versioned `-Merge` states | `DBMS_MIN_REVISION_WITH_MERGE_COMBINATOR_STATE_VERSION` | `54494` | A state of a `-Merge` aggregate function, such as `AggregateFunction(quantileDeterministicMerge, ...)`, is written at state version `0`, whatever version the function it merges has at that revision. |

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 description is controversial.

@alexey-milovidov alexey-milovidov self-assigned this Oct 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai make the description clearer in a follow-up PR when this PR is merged.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. After this PR is merged I will send a follow-up that makes the description of revision 54494 in format.mdx and protocol.mdx state precisely what is sent to and read from a peer below that revision, and link it here.

Merged via the queue into ClickHouse:master with commit 9417c18 Oct 10, 2026
300 of 301 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The follow-up is #125115.

alexey-milovidov pushed a commit to raimannma/ClickHouse that referenced this pull request Oct 12, 2026
The rows describing `DBMS_MIN_REVISION_WITH_MERGE_COMBINATOR_STATE_VERSION`
in `format.mdx` and `protocol.mdx` said that a `-Merge` state is written at
version 0 "whatever version the function it merges has", without naming the
column type, without saying that the version belongs to that type rather than
to the merged function, and without describing the reader.

Each row now names the full type of the partial state a shard sends for a
distributed `quantileDeterministicMerge`, states both directions below the
revision (written at version 0; a type string with no outer version is read at
version 0), and says that a version spelled in the argument type does not
apply to the payload. The protocol row also notes that the binary type
encoding always carries the version.

Checked on a debug build of master over HTTP with `client_protocol_version`
54490/54492/54493/54494 (type strings, binary type encoding, payload bytes)
and with a distributed `quantileDeterministicMerge` against 26.9.9.28 in both
directions.

Requested in ClickHouse#123070 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
JTCunning pushed a commit to JTCunning/ClickHouse that referenced this pull request Nov 3, 2026
The bugs behind their `no-parallel-replicas` / `no-replicated-database` tags are fixed on master:
- `01660_join_or_any`: ClickHouse#123683
- `04653_bloom_filter_fixed_string_constant_scalar`: ClickHouse#118988
- `04819_dynamic_aggregate_function_state_version`: ClickHouse#123649
- `04825_quantile_deterministic_alter_add_modify_column`: ClickHouse#115393, ClickHouse#123070
- `04494_atomic_populate_materialized_view_parallel_replicas`: ClickHouse#124477
- `04266_text_index_tokens_cardinality_order`: ClickHouse#124500 already disables parallel replicas for the log-checked query

Related: ClickHouse#124015
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 comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

quantileDeterministicMerge gives a different result over the network: -Merge states are sent at version 0

4 participants