Skip to content

Serialize serialize_string_in_memory_with_zero_byte in the query plan - #112131

Merged
Avogar merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-112079-serialize-string-zero-byte-in-plan
Aug 14, 2026
Merged

Avogar merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-112079-serialize-string-zero-byte-in-plan

Conversation

@groeneai

@groeneai groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #112079

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixes serialize_string_in_memory_with_zero_byte being dropped from the serialized query plan. With serialize_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::serialize builds a fresh QueryPlanSerializationSettings per step and emits only what
that step's serializeSettings assigned; readBinary leaves an absent name at its declared default.
Both AggregatingStep::deserialize and MergingAggregatedStep::deserialize read
serialize_string_in_memory_with_zero_byte into Aggregator::Params, but neither serializeSettings
ever wrote it - the only Params field those two read without writing.

So with serialize_query_plan = 1 an initiator running the setting at 0 ships a plan the executing
node deserializes as 1. The two then disagree on the aggregation-key byte layout (the flag adds or
removes one trailing byte per string in ColumnString::serializeValueIntoArena), and since the
two-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 a
cluster of incompatible versions is the setting's whole purpose. Only an explicit = 0 diverges,
both defaults being true, which is why nothing observes it today.

The fix adds the missing assignment to both serializeSettings bodies, for both values and at
every 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 omitting true would 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-lts does not, v25.8.13.73-lts backported it, both at version 0). Writing it
always makes such a peer fail closed on the unknown name instead.

The new gtest drives serializeSettings -> writeChangedBinary -> readBinary per step, asserting
the 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: EXPLAIN does
not surface the flag (Aggregator::Params::explain prints only keys and aggregates) and a single-node
query never round-trips a plan, so no query output changes deterministically with the fix. The
existing tests/integration/test_string_aggregation_compatibility does set the setting to 0 against
a pinned older node, but never sets serialize_query_plan, which is why it misses this.

The invariant is: every setting a step's deserialize reads must be written by that same step's
serializeSettings. Because the settings object is per step, a write by one step cannot supply a
read 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:

step read but not written by that step
AggregatingStep serialize_string_in_memory_with_zero_byte - fixed here
MergingAggregatedStep serialize_string_in_memory_with_zero_byte - fixed here
ArrayJoinStep enable_lazy_columns_replication - not in this PR

ArrayJoinStep::deserialize reads enable_lazy_columns_replication, whose only writer is reached
from JoinStepLogical::serializeSettings - a different step, hence a different settings object. It
is 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, RollupStep and AggregatingProjectionStep implement neither serialize nor
serializeSettings, so there is no third carrier of this flag.

Version info

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

`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
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Before opening this PR I ran an independent cold review of the resulting code plus a separate
second-model review pass. Verdicts below; nothing is left unowned.

# Finding Severity Verdict
1 The description claimed that on a same-version cluster a mismatched flag "changes only an internal key layout without producing a wrong result". ⚠️ major ✅ Agreed and corrected in the description. Under two-level aggregation the bucket number is derived from the hash of the serialized key bytes (Aggregator::convertBlockToTwoLevelImpl → Method::State::getHash → TwoLevelHashTable::getBucketFromHash), the bucket travels on the wire (BlockInfo::bucket_num) and bucket-wise merging merges each bucket independently (GroupingAggregatedTransform / MergingAggregatedBucketTransform), so a bucket-assignment divergence duplicates groups. The description now states that consequence with its citations and explains why the oracle is still a gtest, instead of asserting there is no wrong result.
2 The backward-compatibility enumeration went from "26.1 through master" straight to 25.7/25.6, silently skipping 25.8, which SECURITY.md still lists as supported. 💡 nit ✅ Agreed and corrected. 25.8 does declare the setting, so the new entry is decodable there; the only name it does not know is AggregatingStep's pre-existing enable_producing_buckets_out_of_order_in_aggregation write, and MergingAggregatedStep's full write set is known to 25.8. The measurement is now in the description.

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
completeness sweep is deliberately per step, since QueryPlan::serialize builds a fresh
settings object for each step and a write by one step cannot supply a read by another. That sweep
finds one further asymmetry beyond the two fixed here — ArrayJoinStep reading
enable_lazy_columns_replication — which is disclosed in the description and tracked separately
rather than bundled in. This PR does not claim zero residual scope.

Session id: cron:clickhouse-review-slot-50:20260727-142400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes — a gtest, no server, no cluster, no randomization: build/src/unit_tests_dbms --gtest_filter='*SettingsRoundTrip*'. It drives the real production path per step (serializeSettings → writeChangedBinary → a fresh QueryPlanSerializationSettings → readBinary) and asserts the value the executing node would see. Fails on every run of an unfixed build.
b Root cause explained? Yes. QueryPlan::serialize builds a fresh settings object 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 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. So an initiator at = 0 ships a plan the executing node reads back as 1, and the two then disagree on the aggregation-key byte layout (the flag reaches ColumnsHashing → ColumnString::serializeValueIntoArena, where it adds or removes one byte per string). One-directional: 1 round-trips as 1, only an explicit 0 diverges.
c Fix matches root cause? Yes — the defect is the missing assignment, added in the two serializeSettings bodies that declare these steps' setting dependencies. Not a band-aid: making the deserializer fall back to the executing node's own core setting would reintroduce exactly the divergence the plan-settings mechanism exists to prevent, and flipping the declared default to false would make the divergence the DEFAULT for every serialized plan.
d Test intent preserved / new tests added? No existing test changed or weakened (the diff is 2 production files plus 1 new test file). Four new gtests added in src/Processors/QueryPlan/tests/gtest_aggregating_step_settings_roundtrip.cpp — both steps × both values. The existing gtest_aggregating_step_clears_reduced_flag passes the flag positionally and is unaffected (it passed in the regression sweep).
e Both directions demonstrated? Yes. Unfixed (both lines removed): Actual: true / Expected: false for both steps, 2 FAILED / 2 passed. Fixed: 4/4 PASS. Plus a 4-cell matrix: reverting only AggregatingStep.cpp fails only that step's test and leaves the other passing, and symmetrically for MergingAggregatedStep.cpp — so each of the two lines is separately pinned and a partial fix cannot pass. After the matrix the binary rebuilt bit-identically to the pre-matrix Build ID e02d32e6aaa037d653d693630a071104d9fe8437.
f Fix is general across code paths? Yes, and swept per step (a fresh settings object per step means a global "written anywhere?" check is the wrong predicate). Across all 8 src/ files referencing the enum, reads − writes computed within each step now yields zero asymmetries for both aggregation steps (AggregatingStep 21/21, MergingAggregatedStep 8/8); the other five files were already symmetric. One further asymmetry exists on master — ArrayJoinStep reads enable_lazy_columns_replication, written only by JoinStepLogical — and is deliberately not in this PR (different subsystem, opposite default direction, performance-only effect); it is disclosed in the description and tracked separately. Sibling carriers of the flag were enumerated: of the four src/Processors/QueryPlan/ steps holding an Aggregator::Params, only these two are serializable at all (CubeStep/RollupStep implement neither serialize nor serializeSettings), so there is no third carrier.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes — the value is a single bool and the assignment is unconditional, so the input space is exactly {false, true} and both are tested for both steps (4 tests). false is the diverging direction and fails on master; true is the control proving the new write propagates the real value rather than hard-coding one. No type wrappers, engines, formats or boundary values apply to a bool.
h Backward compatible? (maintainer-approved exception only) Yes, measured per step per branch. BaseSettings::readBinary throws on an unknown name, so each step's full write set was diffed against every release branch's declare list: every branch from 26.1 through master declares this setting AND currently has zero names unknown to it written by either step, so the new entry is simply decoded. The only branches lacking the name (25.7, 25.6) are unsupported per SECURITY.md, and on those master's AggregatingStep already writes enable_producing_buckets_out_of_order_in_aggregation, which they do not know — so such a receiver already fails on any aggregating plan from master today, independently of this change. No plan serialization version bump and no SettingsChangesHistory.cpp entry are implied: no setting's default or existence changes, only which settings a step declares as dependencies. Wire grows by one entry on the serialized-plan path only, unconditionally, exactly like every sibling write in both functions.
i Invariants and contracts preserved? Yes, and the change restores one: the serialize/deserialize symmetry contract that every setting a step's deserialize reads is written by that same step's serializeSettings. serializeSettings is a pure writer into a caller-owned, step-local settings object — no error paths, no early returns, no allocation beyond what the 27 sibling assignments already perform, and no concurrency involvement (the object is constructed fresh per step and nothing observes it between the assignment and writeChangedBinary). Non-serialized execution is untouched: those paths pass the value to Aggregator::Params directly.

Session id: cron:clickhouse-impl-slot-7:20260727-134000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @Avogar — could you review this? AggregatingStep::serializeSettings and MergingAggregatedStep::serializeSettings never wrote serialize_string_in_memory_with_zero_byte although both deserialize bodies read it, so with serialize_query_plan = 1 an initiator that disabled the setting shipped a plan the executing node decoded with it enabled and the two disagreed on the aggregation-key byte layout; this adds the missing assignment to both bodies plus a round-trip gtest per step.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3c9cdbb]

Summary: ✅


AI Review

Summary

This PR fixes the original missing-setting bug: both aggregation steps now write serialize_string_in_memory_with_zero_byte, and the new gtest covers the per-step settings round-trip at query-plan serialization version 0 and at the current version. I still see one compatibility risk in the merged shape: MergingAggregatedStep now emits that setting unconditionally, which can make older 25.8 peers reject merge-only numeric-key fragments even though the flag cannot affect those plans.

Missing context / blind spots
  • ⚠️ No local build* directory was present in this checkout, so I could not rerun the new gtests or build an end-to-end mixed-version repro locally.
Findings

⚠️ Majors

  • [src/Processors/QueryPlan/MergingAggregatedStep.cpp:221] [dismissed by author -- https://github.com/Serialize serialize_string_in_memory_with_zero_byte in the query plan #112131#issuecomment-5226289950] This unconditional write widens the old-peer failure surface beyond the string-key cases that actually depend on the flag. serialize_string_in_memory_with_zero_byte only changes ColumnString key serialization, but MergingAggregatedStep::serializeSettings now sends it even for merge plans whose grouping keys cannot serialize any String at all. On v25.8.12.129-lts (same query-plan serialization version 0, no such setting in the schema, and a readBinary that does not cleanly reject unknown names), those numeric-key merge fragments now hit the unknown-setting path for no correctness benefit. Suggested fix: gate this write on whether any grouping key serialization can reach ColumnString, or otherwise prove that MergingAggregatedStep is never shipped to such peers in the serialize_query_plan path.
Tests
  • ⚠️ The new unit test proves the settings round-trip, but it uses a UInt64 header and does not exercise the compatibility boundary changed here: a pre-v25.8.13 receiver decoding a merge-only fragment whose keys never touch ColumnString. A focused serializer test against the old QueryPlanSerializationSettings schema, or a proof that MergingAggregatedStep is never serialized to remote peers in this upgrade window, would close the gap.
Final Verdict

Needs one more compatibility pass before merge: the original bug is fixed, but the current MergingAggregatedStep write looks broader than the behavior it needs to protect.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 83/83 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 63eca35

CI fully finished on this head (Finish Workflow pass, no check queued or in progress). One failure, and it has an owner.

Check / test Reason Owner / fixing PR
Stress test (arm_debug) / Logical error: Inconsistent KeyCondition behavior (STID: 5182-2f27) trunk bug, debug-only assertion in MergeTreeDataSelectExecutor::markRangesFromPKRange on the widening-_CAST monotonic-chain class (canary for #90461); the aborting query is a fuzzed 04612_reverse_key_index_analysis mutation with (_CAST(column 0) in ['5','5']) participating, and this PR's diff touches only AggregatingStep.cpp, MergingAggregatedStep.cpp and a new gtest #109023 (ours, merged 2026-07-27T20:22Z) — merged master @ 04640b28556d13f0aa0809bfd516145607d63073 to pick it up

The failing build predates that merge: this head's merge-base with master was 1d4408f794c3 (2026-07-27 04:40Z) and the stress job started 21:01Z with the pre-fix tree, so matchesExactContinuousRange still lacked the empty-chain guard (mapping.functions.empty() count 0 at 63eca351, 1 after the merge). CI is re-running on the new head.

Session id: cron:our-pr-ci-monitor:20260727-220000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 04640b2

CI fully finished on this head (Finish Workflow success, 174 check-runs, 0 queued/in progress).
Every failure below has an owner.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Cannot start clickhouse-server + Check failed Startup metadata load aborts on Invalid storage definition in metadata file for the fuzzer-created parameterized view test_5.04105_pv_nested_outer__fuzz_4, whose body is an EXCEPT. Deterministic: the same victim table on 10/10 server restarts, one signature, no signal and no sanitizer report. ASTSelectWithUnionQuery::hasQueryParameters() only inspects children castable to ASTSelectQuery, so an EXCEPT/INTERSECT body makes isParameterizedView() false at load time. Both rows are one event, so one line. #112211 (ours, open)

Not caused by this pull request: the diff is AggregatingStep.cpp (+1), MergingAggregatedStep.cpp (+1) and one new gtest, with nothing under src/Parsers/ or src/Databases/, and the victim view comes from 04105_explain_syntax_parameterized_view.sql, which this pull request does not touch. #112211 is not merged yet, so the recurrence on this head is expected rather than a failed fix, and there is nothing to pick up by merging master.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master (conflict resolution)

AggregatingStep::serializeSettings conflicted with 21d8a62 ("Serialize
enable_parallel_single_level_merge in the query plan"), which added its own write at the same
insertion point. The two writes are independent, so both are kept; AggregatingStep::deserialize
already reads both. MergingAggregatedStep.cpp merged cleanly. Head 04640b2 -> 3f90969,
a fast-forward, and the change against master is still exactly the same 3 files (+142).

Re-verified on the merged tree:

  • the gtest passes 4/4, and the mutation matrix still holds per line: removing both production
    lines fails both ...FalseSurvives tests, removing only one fails exactly that step's test, and
    restoring rebuilds bit-identically (Build ID 9c9ee7a2e684).
  • the per-step asymmetry sweep now reports AggregatingStep 22 writes / 22 reads and
    MergingAggregatedStep 8 / 8; on master both are still one write short. ArrayJoinStep remains
    the third, still out of scope.
  • regression sweep over the aggregation/query-plan/serialization gtest suites: 111 passed,
    0 failed, 9 pre-existing skips.

Three counts in the description were staled by the merge and are corrected: AggregatingStep is
now 22/22 rather than 21/21; all 80 declared settings are used in code (the earlier 79 undercounted,
the declare macro's own parameter name is not a setting); and the backward-compatibility section now
enumerates the branches SECURITY.md actually lists as supported (25.8, 26.3, 26.5, 26.6, 26.7)
rather than "26.1 through master". That last correction matters in one direction worth stating:
master's new enable_parallel_single_level_merge write is unknown to every release branch today,
so an aggregating plan from master already fails on those receivers independently of this PR. The
set of names a supported receiver cannot decode is the same before and after this change.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3f90969

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 00084_external_aggregation query-level Code: 241 memory-limit: the test's own max_memory_usage left no headroom for the AggregatingTransform chunk #112054 (external, merged) - merged master to pick it up

Sole red on this head: 174 check-runs, 149 success, 24 skipped, 1 failure, Finish Workflow
green.

Not caused by this PR, which only serializes two settings into the query plan
(AggregatingStep, MergingAggregatedStep) plus a gtest, and cannot change a query's memory
budget. The failure is the query-level form, Query memory limit exceeded: would use 318.44 MiB (attempt to allocate chunk of 64.06 MiB), maximum: 286.10 MiB ... While executing AggregatingTransform, which is distinct from the host-level (total) memory limit exceeded
signature that shares this test name. The runner re-ran it 21 times at the same randomized
settings and all 21 passed, which is what a too-tight budget looks like rather than a code
defect.

#112054 ("Give 00084_external_aggregation real memory headroom") raises exactly that budget
and merged at 2026-07-28T19:14:40Z, about five and a half hours AFTER this job ran at 13:43:12Z,
so the tested build predates the fix. It was not an ancestor of this head, so I merged master to
pick it up: new head 40ed6e35cc3357c9d8ee303a4330e7acddc91c9c, which now contains
21bb47e6f725406c0232c7c0e6919d03943cc7e8. CI will re-run on that head.

Verified before merging: zero submodule or .gitmodules drift introduced (the gitlink diff
against the merged master tip is empty), and the only files differing from master are the three
this PR owns.

Session id: cron:our-pr-ci-monitor:20260728-193000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 65/65 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 40ed6e3

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit deterministic under parallel replicas (Failed 3 out of 3 reruns) #112385 (mine, open)
Sync - CH Inc sync (private, not actionable)

The 00084_external_aggregation line from the previous ledger is resolved: this head merged master
and now contains #112054, and that test passed on this run.

Not PR-caused. My diff serializes two settings into the query plan (AggregatingStep,
MergingAggregatedStep) plus a gtest; it cannot affect the per-table concurrency throttle that
01666 asserts. All 153 completed non-skipped checks other than that one are green.

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.
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

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 3c9cdbb18315161b47e543d34c0c1e03ba978859.

The merge

One conflict, in MergingAggregatedStep::serializeSettings: master had added its own version-gated write of enable_packed_string_keys_in_aggregation at the same insertion point. Two independent additions, so both are kept. Master also changed serializeSettings to take a UInt64 version and added a parameter to the merge-only Aggregator::Params constructor; the test was adapted to both. AggregatingStep.cpp auto-merged.

Re-verified the bug is still live rather than fixed by the drift: on today's master both steps still read serialize_string_in_memory_with_zero_byte and neither serializeSettings writes it.

The correction

I 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 true. That is true only of a receiver that declares the name. v25.8.12.129-lts does not, and its GROUP BY key path (serializeKeysToPoolContiguous -> ColumnString::serializeValueIntoArena) takes no serialization settings and writes no trailing zero byte, so it behaves exactly like false. Omitting true towards such a peer would have silently handed it the other key layout, re-creating this PR's own bug in the direction that used to be safe. v25.8.13.73-lts backported the setting and defaults it to true, yet both advertise query-plan serialization version 0, so no gate can be built on the version either.

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.

Verification

Roundtrip and wire tests 5/5, master's sibling PackedStringKeysPlanSetting 6/6, and the sweep over *Aggregat*:*QueryPlan*:*Serializ*:*Settings*:*PackedString* is 150 passed / 0 failed (9 pre-existing source-level skips in an untouched file).

Mutation matrix on the merged tree, each arm a distinct Build ID: removing both lines fails both FalseSurvives tests plus the wire test; removing only one fails exactly that step's test and leaves the other green; restoring rebuilds bit-identically. The omit-the-default form is also pinned now - reintroducing it reddens the wire test at version 0 only. No submodule pin drift (diff --name-only origin/master..HEAD -- contrib .gitmodules is empty) and the diff is the three intended files.

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-v25.8.13 servers. MergingAggregatedStep's own merge params carry neither the input's bucket layout nor the producing steps' thresholds - the comment master added directly below my change says exactly that - so a key-type predicate there would trade a hard error for a silent wrong-results path. The related observation that v25.8.12's readBinary indexes field_infos[SIZE_MAX] rather than throwing on an unknown name is correct, but master already writes names that release does not declare from both steps (three from AggregatingStep, one from MergingAggregatedStep), so that path is pre-existing and this change does not widen it. Negotiating a schema capability would be a protocol-level change well beyond this fix.

@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3c9cdbb18 with master c8cea90a1 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2999ffda7; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: compile time of recompiled translation units.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.38 MiB 687.39 MiB -2.99 MiB (-0.43%)

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 sizes

505 object files changed (+299.42 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/HiveTextRowOutputFormat.cpp.o new 148.12 KiB +148.12 KiB
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationMap.cpp.o 2.16 MiB 2.18 MiB +21.09 KiB (+0.96%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationArray.cpp.o 228.85 KiB 249.85 KiB +21.00 KiB (+9.18%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationTuple.cpp.o 271.66 KiB 292.33 KiB +20.66 KiB (+7.61%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units ⚠️

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

Translation units without a recent master baseline:

  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp: 25.0 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp: 10.5 s
  • contrib/vectorscan-cmake/__/vectorscan/src/nfagraph/ng_violet.cpp: 6.5 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp: 6.2 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/executor/instantiate/component/component.cpp: 5.9 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/CodeGen/AssignmentTrackingAnalysis.cpp: 5.7 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/utils/TableGen/GlobalISelEmitter.cpp: 5.7 s
  • contrib/s2geometry-cmake/__/s2geometry/src/s2/s2builder.cc: 5.6 s
  • contrib/ai-sdk-cpp-cmake/__/ai-sdk-cpp/src/providers/openai/openai_factory.cpp: 5.6 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/executor/engine/threadInstr.cpp: 5.4 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/executor/instantiate/table.cpp: 5.3 s
  • contrib/vectorscan-cmake/__/vectorscan/src/rose/rose_build_program.cpp: 5.0 s

Job report

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3c9cdbb

CI is fully finished on this head and there are no failures: 151 success / 23 skipped / 0 failure of 174 check-runs, Finish Workflow green. No CH Inc sync row on this head either, so there is not even an exempt line.

Check / test Reason Owner / fixing PR
(none) - -

Gate detail: (a) 0 check-runs queued or in_progress across all 174 (fully paginated); (b) Finish Workflow = success at 2026-08-08T17:48:40Z; (c) 49 minutes since the last completion, past the 20-minute CIDB ingestion buffer; (d) trivially satisfied.

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

@Avogar
Avogar added this pull request to the merge queue Aug 14, 2026
Merged via the queue into ClickHouse:master with commit 9fdec34 Aug 14, 2026
180 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer

Shell reproducer — set BIN to a ClickHouse binary path and run with bash; requires the referenced test fixtures from the repo.

#!/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 2

Results:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3, 25.8
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • Fix merged on master (not re-verified: tested master build predates this PR's merge — a clean verdict is not attributable to the fix). The releases listed above still have the bug and need the backport.

CC component owner: @davenger @KochetovNicolai

Analysis metadata

comp-query-optimizer · Severity P2 · Finding phase_d_pr112131

  • Verified against master build a22169382ef9 (aarch64)
  • Could not test: master
Introducing change: not identified
  • Secondary components: comp-aggregation

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed on all five active release branches, re-measured rather than taken from the report.
Official builds from builds.clickhouse.com, your reproducer plus
<memory_worker_use_cgroup>0</memory_worker_use_cgroup> (without it the server sizes its limit from
the whole cgroup and dies with Code 241 before the query runs):

build version groups (expected 2000)
master 26.8.1.1515 (84275634fce) 2000
26.7 26.7.4.47 2005
26.6 26.6.3.44 2005
26.5 26.5.7.57 2005
26.3 26.3.18.32 2005
25.8 25.8.30.20 2005

The master arm is the one you left open: that build has 9fdec3420 as an ancestor, so the clean
verdict is attributable to the fix. Controls on 26.7 and 25.8 both return 2000
(serialize_string_in_memory_with_zero_byte=1 with plan serialization on, and =0 with
serialize_query_plan=0), so 2005 comes from the setting crossing the plan boundary, not from the
fixture.

v25.8-must-backport is the single correct label: select_backport_branches expands it to exactly
those five branches.

The automated cherry-pick will conflict on every branch, though.
git merge-tree --merge-base=<merge commit>^1 <branch> <merge commit> conflicts in both
AggregatingStep.cpp and MergingAggregatedStep.cpp for all five: serializeSettings gained its
UInt64 version parameter after they branched, and the added line sits next to master-only code
(enable_packed_string_keys, enable_adaptive_aggregator). The release-branch form is one
unconditional line per file inside the version-less signature, without the packed-string-keys
block. The gtest does not port as written either, since enable_packed_string_keys is absent from
Aggregator.h on all five and src/Processors/QueryPlan/tests/ does not exist on 26.5, 26.3 or
25.8.

@Avogar could you apply v25.8-must-backport? I do not hand-author release-branch PRs, so I will
pick up the cherry-pick PRs the robot opens and resolve the conflicts there.

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-bugfix Pull request with bugfix, not backported by default 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.

AggregatingStep and MergingAggregatedStep don't serialize serialize_string_in_memory_with_zero_byte into the query plan

5 participants