Repository navigation
Conversation
`QueryPlan::serialize` builds a fresh `QueryPlanSerializationSettings` per step and `writeChangedBinary` emits only entries whose `changed` flag is set, which `SettingFieldNumber::operator=` sets unconditionally. So only what a step's `serializeSettings` assigns reaches the wire, and on the receiving side `readBinary` leaves an absent name at its declared default. `serialize_string_in_memory_with_zero_byte` declares `true` and is read by both `AggregatingStep::deserialize` and `MergingAggregatedStep::deserialize`, but was written by neither `serializeSettings` - every other `Aggregator::Params` field those two functions carry is written, this one was read-only. With `serialize_query_plan = 1` an initiator running the setting disabled therefore ships a plan the executing node deserializes with it enabled, and the two disagree on the aggregation-key byte layout: the flag reaches `ColumnsHashing` and from there `ColumnString::serializeValueIntoArena`, where it adds or removes one byte per string. Keeping that layout consistent across a cluster of incompatible versions is the setting's only purpose. The divergence is one-directional - both the core setting and the plan setting default to `true`, so an initiator at `1` round-trips as `1` and only an explicit `0` diverges, which is why nothing observes this today. Add the missing assignment to both `serializeSettings` bodies and a gtest that drives the real round trip per step, for both values. The `false` direction fails without the fix; reverting either production line fails exactly that step's test, so each line is separately pinned. A per-step sweep of every `QueryPlanSerializationSetting` read against the writes of the same step finds one further asymmetry, `ArrayJoinStep` reading `enable_lazy_columns_replication`. It is a different subsystem with the opposite default direction and a performance-only effect, and is tracked separately rather than bundled here. Closes: ClickHouse#112079
Internal second-model review (click to expand)Before opening this PR I ran an independent cold review of the resulting code plus a separate
The second-model pass returned no findings on this change set. Also worth stating explicitly, because it is the question the issue implicitly asks: the Session id: cron:clickhouse-review-slot-50:20260727-142400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260727-134000 |
|
cc @nihalzp @Avogar — could you review this? |
|
Workflow [PR], commit [3c9cdbb] Summary: ✅
AI ReviewSummaryThis PR fixes the original missing-setting bug: both aggregation steps now write Missing context / blind spots
Findings
Tests
Final VerdictNeeds one more compatibility pass before merge: the original bug is fixed, but the current LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 83/83 (100.00%) · Uncovered code |
…ion behavior stress failure (ClickHouse#109023)
CI finish ledger — 63eca35CI fully finished on this head (Finish Workflow pass, no check queued or in progress). One failure, and it has an owner.
The failing build predates that merge: this head's merge-base with master was Session id: cron:our-pr-ci-monitor:20260727-220000 |
CI finish ledger — 04640b2CI fully finished on this head (Finish Workflow success, 174 check-runs, 0 queued/in progress).
Not caused by this pull request: the diff is Session id: cron:our-pr-ci-monitor:20260728-070000 |
Conflict in AggregatingStep::serializeSettings: master added enable_parallel_single_level_merge at the same insertion point where this branch adds serialize_string_in_memory_with_zero_byte. The two writes are independent, so both are kept; AggregatingStep::deserialize already reads both.
Merged master (conflict resolution)
Re-verified on the merged tree:
Three counts in the description were staled by the merge and are corrected: |
…e-string-zero-byte-in-plan
CI finish ledger - 3f90969Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Sole red on this head: 174 check-runs, 149 success, 24 skipped, 1 failure, Not caused by this PR, which only serializes two settings into the query plan #112054 ("Give Verified before merging: zero submodule or Session id: cron:our-pr-ci-monitor:20260728-193000 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 65/65 (100.00%) · Uncovered code |
CI finish ledger - 40ed6e3Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The Not PR-caused. My diff serializes two settings into the query plan ( Session id: cron:our-pr-ci-monitor:20260729-023000 |
…e-string-zero-byte-in-plan # Conflicts: # src/Processors/QueryPlan/MergingAggregatedStep.cpp
`QueryPlanSerializationSettings` is a strict named schema: `readBinary` throws on a name it does not know, and an absent name is left at its declared default, which for `serialize_string_in_memory_with_zero_byte` is `true`. So only the `false` value has to reach the executing node; emitting the default as well would make every aggregating plan unreadable by a receiver that predates the name, for no gain. The receiver cannot be selected on the query-plan serialization version here. Measured over the release tags: `v25.8.12.129-lts` does not declare the name and `v25.8.13.73-lts` does, yet both advertise version 0, so the version does not discriminate. Writing `false` unconditionally is nonetheless correct - a peer that cannot honour `false` fails closed on the unknown name rather than silently aggregating String keys with the other in-memory representation, whose hash values and two-level bucket numbering differ. Found by the second-model review of the master merge.
The helpers hardcoded the current version, so a regression that emitted the setting only from version 1 upwards would have passed while silently dropping `false` for `v25.8.13.73-lts`, which knows the name but advertises version 0. The version is now a parameter and the test asserts both directions at version 0 as well as at the current one.
The previous commit wrote only `false`, on the argument that an absent name leaves the receiver at the declared default `true`. That is true of a receiver that declares the name, and wrong of the receivers the argument was meant to protect. `v25.8.12.129-lts` does not declare the setting, and its GROUP BY key path (`serializeKeysToPoolContiguous` -> `ColumnString::serializeValueIntoArena`) takes no serialization settings and writes no trailing zero byte - it behaves exactly like `serialize_string_in_memory_with_zero_byte = false`. Omitting `true` towards such a peer therefore does not leave it at `true`; it silently hands it the other key layout, which is the divergence this PR exists to close. `v25.8.13.73-lts` backported the setting (ClickHouse#90880) and does default it to `true`, yet both advertise query-plan serialization version 0, so `version` cannot tell the two apart and no gate can be built on it. So the assignment goes back to unconditional, and the test now requires the name on the wire for both values at version 0 as well as at the current version. Reverting either production line still fails exactly that step's round-trip test. Found by the second-model review, which caught the bad premise in the previous commit.
The file header said `readBinary` leaves an absent name at its declared default `true`, which is only true of a receiver that declares the name; a receiver predating it behaves like `false`. Removed that half and cut the surrounding comments back to what is not obvious at the call site.
|
Merged master (the branch was 5177 commits behind) and reworked the fix after a second-model review found a real compatibility bug in it. New head The mergeOne conflict, in Re-verified the bug is still live rather than fixed by the drift: on today's master both steps still read The correctionI had briefly changed the write to fire only for the non-default value, reasoning that an absent name leaves the receiver at the declared default So the production change is back to the plain unconditional assignment in both bodies, and the test now requires the name on the wire for both values at version 0 as well as at the current version. Net production delta: two lines. VerificationRoundtrip and wire tests 5/5, master's sibling Mutation matrix on the merged tree, each arm a distinct Build ID: removing both lines fails both Two review findings I did not act on, recorded rather than silently dropped. Both ask for the old-peer write to be narrowed by key type so that numeric-key plans stay readable by pre- |
Build profile diff (arm_release)Comparing Binary sizes
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. Object file sizes505 object files changed (+299.42 KiB total), 1 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units
|
CI finish ledger - 3c9cdbbCI is fully finished on this head and there are no failures: 151 success / 23 skipped / 0 failure of 174 check-runs,
Gate detail: (a) 0 check-runs queued or in_progress across all 174 (fully paginated); (b) This is the first head after the master merge and the compatibility rework described in the comment above. Ball is now with the reviewer. Session id: cron:our-pr-ci-monitor:20260808-183000 |
ReproducerShell reproducer — set #!/bin/bash
BIN="${BIN:-./clickhouse}" # path to the ClickHouse binary under test
# PR #112131: AggregatingStep/MergingAggregatedStep read
# serialize_string_in_memory_with_zero_byte on plan deserialization but never wrote it
# on serialization. With serialize_query_plan=1 the executing node therefore resolves it
# to its default (1) while the initiator uses the session value (0); the two-level bucket
# number hashes the serialized key bytes, so a key present on both shards lands in two
# different buckets and is returned twice.
#
# Two shards on one server (distinct default_database), one past the two-level threshold
# and one below it, so the initiator re-buckets the single-level chunk with its own layout.
set -uo pipefail
W=$(mktemp -d)
P=$(( 21000 + RANDOM % 9000 ))
trap 'kill %1 2>/dev/null; rm -rf "$W"' EXIT
cat > "$W/config.xml" <<XML
<clickhouse>
<logger><level>none</level><console>false</console><log>$W/ch.log</log><errorlog>$W/err.log</errorlog></logger>
<tcp_port>$P</tcp_port>
<process_query_plan_packet>1</process_query_plan_packet>
<listen_host>127.0.0.1</listen_host>
<path>$W/data/</path>
<tmp_path>$W/tmp/</tmp_path>
<user_files_path>$W/uf/</user_files_path>
<mark_cache_size>536870912</mark_cache_size>
<users><default><password></password><profile>default</profile><quota>default</quota><networks><ip>::/0</ip></networks></default></users>
<profiles><default></default></profiles>
<quotas><default/></quotas>
<remote_servers>
<two>
<shard><replica><host>127.0.0.1</host><port>$P</port><default_database>db1</default_database></replica></shard>
<shard><replica><host>127.0.0.1</host><port>$P</port><default_database>db2</default_database></replica></shard>
</two>
</remote_servers>
</clickhouse>
XML
"$BIN" server --config-file="$W/config.xml" >"$W/stdout.log" 2>&1 &
CL() { timeout 60 "$BIN" client --host 127.0.0.1 --port "$P" "$@"; }
for _ in $(seq 1 40); do CL -q "SELECT 1" >/dev/null 2>&1 && break; sleep 1; done
CL -q "SELECT 1" >/dev/null 2>&1 || { echo "OBSERVED: server did not start -- inconclusive"; exit 2; }
SETUP=$(CL -mn -q "
CREATE DATABASE db1; CREATE DATABASE db2;
CREATE TABLE db1.t (id UInt64, s1 String) ENGINE=MergeTree ORDER BY id;
CREATE TABLE db2.t (id UInt64, s1 String) ENGINE=MergeTree ORDER BY id;
INSERT INTO db1.t SELECT number, concat('key_value_', toString(number)) FROM numbers(2000);
INSERT INTO db2.t SELECT number, concat('key_value_', toString(number)) FROM numbers(5);
CREATE TABLE default.dist (id UInt64, s1 String) ENGINE=Distributed(two, '', t);
" 2>&1)
[ -n "$SETUP" ] && { echo "OBSERVED: setup failed: $SETUP"; exit 2; }
OUT=$(CL -q "SELECT count() FROM (SELECT id, s1 FROM default.dist GROUP BY id, s1)
SETTINGS serialize_query_plan=1, serialize_string_in_memory_with_zero_byte=0,
group_by_two_level_threshold=100, distributed_aggregation_memory_efficient=1,
prefer_localhost_replica=0" 2>&1)
RC=$?
echo "groups=$OUT (expected 2000)"
[ "$RC" = "124" ] && exit 2
echo "$OUT" | grep -qiE "exception|Code: [0-9]+|NOT_IMPLEMENTED|Unknown setting" && {
echo "OBSERVED: query errored -- setting/plan serialization not supported on this build"; exit 2; }
[ "$OUT" = "2000" ] && { echo "OBSERVED: 2000 groups -- clean"; exit 0; }
[[ "$OUT" =~ ^[0-9]+$ ]] && [ "$OUT" -gt 2000 ] && {
echo "OBSERVED: $OUT groups -- keys duplicated across two-level buckets, bug present"; exit 1; }
echo "OBSERVED: unexpected output -- inconclusive"
exit 2Results:
CC component owner: @davenger @KochetovNicolai Analysis metadata
Introducing change: not identified
|
|
Confirmed on all five active release branches, re-measured rather than taken from the report.
The master arm is the one you left open: that build has
The automated cherry-pick will conflict on every branch, though. @Avogar could you apply |
Closes: #112079
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
serialize_string_in_memory_with_zero_bytebeing dropped from the serialized query plan. Withserialize_query_plan = 1, a cluster running with the setting disabled could diverge on the in-memory string representation between the initiator and the node executing the deserialized plan, because the setting was read on deserialization but never written on serialization and therefore always resolved to its default on the executing node.Description
QueryPlan::serializebuilds a freshQueryPlanSerializationSettingsper step and emits only whatthat step's
serializeSettingsassigned;readBinaryleaves an absent name at its declared default.Both
AggregatingStep::deserializeandMergingAggregatedStep::deserializereadserialize_string_in_memory_with_zero_byteintoAggregator::Params, but neitherserializeSettingsever wrote it - the only
Paramsfield those two read without writing.So with
serialize_query_plan = 1an initiator running the setting at0ships a plan the executingnode deserializes as
1. The two then disagree on the aggregation-key byte layout (the flag adds orremoves one trailing byte per string in
ColumnString::serializeValueIntoArena), and since thetwo-level bucket number hashes those serialized bytes, disagreeing sources can place one logical key
in different buckets - the duplicated-group shape documented in
tests/integration/test_string_aggregation_compatibility. Keeping that layout consistent across acluster of incompatible versions is the setting's whole purpose. Only an explicit
= 0diverges,both defaults being
true, which is why nothing observes it today.The fix adds the missing assignment to both
serializeSettingsbodies, for both values and atevery serialization version. Restricting it to the non-default value is wrong: a receiver predating
the name has no such setting and its GROUP BY key path writes no trailing zero byte at all, so it
behaves like
false, and omittingtruewould silently hand exactly that peer the other layout.Gating on the version fails too: patch releases inside one version disagree on whether they know the
name (
v25.8.12.129-ltsdoes not,v25.8.13.73-ltsbackported it, both at version 0). Writing italways makes such a peer fail closed on the unknown name instead.
The new gtest drives
serializeSettings->writeChangedBinary->readBinaryper step, assertingthe round-tripped value and that the name reaches the wire, for both values and at version 0 as well
as the current one. Reverting either production line fails that step's test.
Why a gtest, and a sibling asymmetry deliberately not fixed here
A gtest rather than a functional or integration test, because the divergence is silent:
EXPLAINdoesnot surface the flag (
Aggregator::Params::explainprints only keys and aggregates) and a single-nodequery never round-trips a plan, so no query output changes deterministically with the fix. The
existing
tests/integration/test_string_aggregation_compatibilitydoes set the setting to0againsta pinned older node, but never sets
serialize_query_plan, which is why it misses this.The invariant is: every setting a step's
deserializereads must be written by that same step'sserializeSettings. Because the settings object is per step, a write by one step cannot supply aread by another, so the sweep is per step rather than a global "is this name written anywhere?"
check. It finds three asymmetries on master, not two:
AggregatingStepserialize_string_in_memory_with_zero_byte- fixed hereMergingAggregatedStepserialize_string_in_memory_with_zero_byte- fixed hereArrayJoinStepenable_lazy_columns_replication- not in this PRArrayJoinStep::deserializereadsenable_lazy_columns_replication, whose only writer is reachedfrom
JoinStepLogical::serializeSettings- a different step, hence a different settings object. Itis another subsystem, its default direction is the opposite, and its effect is performance rather
than correctness, so it needs a different justification, oracle and changelog category. Tracked
separately.
Also checked: of the steps holding an
Aggregator::Params, only these two are serializable at all.CubeStep,RollupStepandAggregatingProjectionStepimplement neitherserializenorserializeSettings, so there is no third carrier of this flag.Version info
26.8.1.1435(included in26.8and later)