Skip to content

Fix LOGICAL_ERROR reading a bucketed Map inside a Dynamic column - #113514

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-dynamic-map-serialization-version-pool-key
Aug 11, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-dynamic-map-serialization-version-pool-key

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #113914

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):

Stopped writing a part whose Map layout contradicts its own metadata, for a Map value inside a Dynamic column. Tables differing only in map_serialization_version shared one cached serialization object, so a part could get the basic Map layout while its metadata declared with_buckets, and reading it later failed with LOGICAL_ERROR: Stream ...buckets_info ... is not found. Parts an earlier version already wrote this way stay unreadable and have to be dropped.

Description

Two tables of the same Dynamic type but different map_serialization_version shared one cached serialization object, because the cache key omitted that setting.

SerializationDynamic objects are interned in SerializationObjectPool, keyed only on SerializationDynamic::getHash with no key-equality check on a hit. That hash mixes in SerializationInfoSettings::updateHash, which hashed 7 of its 8 semantic fields and omitted map_serialization_version, while the defaulted operator== does compare it. Whichever version built the object first therefore served every later user in the process.

The result is a part that contradicts its own metadata: a table declaring with_buckets reused a basic-configured object, wrote the plain Array(Tuple) streams, and still recorded with_buckets in serialization.json. Once the pooled object is rebuilt (restart, DETACH/ATTACH, or a later process) the read asks for the .buckets_info stream the part never wrote and MergeTreeReaderWide::getStream raises LOGICAL_ERROR. A single table reaches this, because map_serialization_version_for_zero_level_parts keeps INSERT parts basic while merged parts use with_buckets.

The fix hashes the field. The other consumers (SharedPartColumns) already compare the full key and are unaffected; one pool entry can now split into two. No on-disk format change.

Scope: this stops such a part from being written. It does not make one an earlier version already wrote readable, because the read follows the part's own serialization.json: that part still raises the same error on a fixed build, changing the table's map_serialization_version does not help, and OPTIMIZE cannot rewrite it, so those parts have to be dropped. Making them readable needs a separate decision on the read path.

Validated with a deterministic reproducer (aborts on unpatched master 3/3, passes with the fix), a mutation arm reverting only the added line (which reddens the stateless test on both the write and the read side), and 50/50 randomized runs of that test.

Version info

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

SerializationDynamic objects are interned in SerializationObjectPool, keyed
only on SerializationDynamic::getHash with no key-equality check on a hit.
That hash mixes in SerializationInfoSettings::updateHash, which hashed seven
of its eight semantic fields and omitted map_serialization_version, while the
defaulted operator== does compare it. So Dynamic(max_types=N) built with
map_serialization_version = with_buckets and the same type built with basic
hashed identically and shared one pooled object; whichever version constructed
it first served every later user in the process.

The result is a part that contradicts its own metadata. A table declaring
with_buckets that reused a basic-configured object wrote the plain
Array(Tuple) streams and still recorded with_buckets in serialization.json.
Reading that part once the pooled object is rebuilt from the table's own
settings (a restart, a DETACH/ATTACH, or any later process) takes the
non-BASIC branch in SerializationMap::deserializeBinaryBulkStatePrefix, asks
for the .buckets_info stream the part never wrote, and
MergeTreeReaderWide::getStream raises LOGICAL_ERROR because the column is
present in the part's column list. In debug and sanitizer builds that aborts
the server. Observed as three Stress test failures on 2026-08-05 across three
unrelated pull requests, driven by the AST fuzzer, which randomizes
map_serialization_version per query. The two versions also coexist by design:
map_serialization_version_for_zero_level_parts exists so INSERT parts stay
basic while merged parts use with_buckets.

Fix by hashing the field. The key can now only become more injective, so one
pool entry may split into two and none can merge. The two SharedPartColumns
hashes that also call updateHash already compare the full key on a collision
and are left alone; the change only makes their sharing more precise. No
on-disk format is affected: all three consumers are in-memory caches and
serialization.json persists the field rather than a hash of it, so no
SettingsChangesHistory entry and no format version bump are required.

Two tests are added. A gtest pins the pool key directly, asserting that the
two Map versions produce different hashes and different pooled objects, with a
positive control (a field that is already hashed does separate them) and a
negative control (equal settings still share one object, so the assertions
cannot be satisfied by breaking interning). A stateless test reproduces the
abort end to end and also asserts the written part carries the bucketed
streams its metadata declares.
@groeneai

groeneai commented Aug 5, 2026

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

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own
cold review of the resulting code, done before reading the implementation notes.
Both raised no blocker and no major on this diff.

# Sev Finding Verdict Evidence / action
1 💡 The stateless test leaves two pool-key fields (string_serialization_version, nullable_serialization_version) unpinned, so randomization could in principle break the collision the test depends on. DISAGREE Both are injected once per test process, so the two CREATE statements in one run get identical values and the collision precondition holds; the DDL pins win over injection because the client only adds settings the DDL has not set. Confirmed empirically: 50 of 50 randomized runs pass, and the mutation arm still reddens the test under full randomization.
2 💡 Are there sibling pooled serializations with the same missing-field defect? DISAGREE Enumerated independently: SerializationDynamic is the only serialization that stores a whole SerializationInfoSettings, and getHash(size_t, const SerializationInfoSettings &) has exactly one declaration in the tree. The siblings each hash the single version field they consume. The two SharedPartColumns hashes compare the full key, so a stale hash there could only miss sharing, never share unequal keys.

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

Additional checks I ran on top of the gate, all clean: the hashed field set now equals the
compared field set exactly; the pool look-up has no key-equality fallback, so a hash collision is
an object identity collision; the abort message and the four load-bearing stack frames of the
local reproducer match the CI report; the mutation arm that reverts only the added line reddens
both the write-side assertion and the read; no serialization hash is persisted into part metadata,
so no format or compatibility surface is touched; and the new gtest file is picked up by the
existing gtest*.cpp glob with no build wiring change.

Session id: cron:clickhouse-review-slot-48:20260805-144700

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two tables of the same Dynamic(max_types=128) type, one declaring map_serialization_version = 'basic' and one 'with_buckets'; insert into the basic one first, then into the bucketed one, then DETACH/ATTACH and read the column. Aborts 3 of 3 runs on unpatched master with the byte-identical CI message Stream y.Map%28UInt64%2C%20UInt64%29.buckets_info for column y with type Dynamic(max_types=128) is not found, and the local stack matches the CI stack frame for frame at MergeTreeReaderWide.cpp:376 <- SerializationMap.cpp:912 <- SerializationVariant.cpp:271 <- SerializationDynamic.cpp:373. Committed as 04753_dynamic_map_buckets_pooled_serialization.
b Root cause explained? SerializationInfoSettings::updateHash hashed 7 of its 8 semantic fields and omitted map_serialization_version, while operator== (defaulted) does compare it. That hash is the sole key of the SerializationDynamic pool (getHash -> ISerialization::pooled -> SerializationObjectPool::getOrCreate, a flat_hash_map<UInt128, weak_ptr> with no key-equality check on a hit), so one object served both Map formats. A table declaring with_buckets that reused a basic-configured object wrote the plain Array(Tuple) streams while recording with_buckets in serialization.json; reading that part once the pooled object is rebuilt asks for the .buckets_info stream it never wrote.
c Fix matches root cause? Yes. The defect is a cache-key defect (a field that changes the constructed object is absent from the key identifying it), so it is fixed in the key: one line hashing the field. Proven load-bearing by a mutation arm that reverts only that line, which reddens both new tests. The band-aid alternative (make SerializationMap tolerate a missing .buckets_info) was rejected: bucketed data lives under Bucket substreams whose names are disjoint from basic's, so a tolerant reader would mis-read rather than abort.
d Test intent preserved / new tests added? Nothing weakened, disabled, or blanket-tagged. Two new tests: a gtest pinning the pool key (DynamicPooledSerialization.PoolKeyDistinguishesMapSerializationVersion) and the end-to-end .sql, whose first assertion also pins the written part layout via system.parts_columns.substreams. The gtest carries two load-bearing controls: a positive one, where a field that is hashed does separate the objects, and a negative one, where equal settings still share one object, so the test cannot be satisfied by breaking interning.
e Both directions demonstrated? Yes, Build ID asserted (SELECT lower(buildId()) == readelf -n) before every verdict. Pristine master 72b3babb…: bucketed streams 0, read ABORTS (3/3). Mutant b457ea5e…: streams 0, .sql prints 0 0 0 then the server dies with the same abort. Fixed 72150f7a…: streams present, read returns 64 64, .sql matches its reference. After reverting the mutant the Build ID returned exactly to 72150f7a…, proving the arms used genuinely different binaries and that the shipped tree is the measured one.
f Fix is general across code paths? SerializationInfoSettings::updateHash has exactly 3 consumers in src/. Only the Dynamic pool lacks a key-equality fallback, and it is fixed. The two SharedPartColumns hashes key unordered_maps whose operator== is defaulted over the full key, and normalizeSettingsForKey deliberately preserves map_serialization_version, so they were already correct and are intentionally untouched (the fix only makes their sharing more precise). ISerialization::pooled's other 19 callers pass no SerializationInfoSettings. Re-verified mechanically that no other field of the struct is missing from the hash, so this is one field, not a class.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured 5 nested shapes inside Dynamic, each on a freshly restarted server per arm (an abort kills the server, so a shared server voids later arms). Pre-fix ABORT / post-fix OK with the correct bucketed layout for Map(UInt64,UInt64), Array(Map(...)), Tuple(Map(...)) and Map(UInt64, Array(UInt64)), i.e. 4 of 4 carriers. Nullable(Map(...)) is a measured non-carrier in both arms (the fixture never materialises a Dynamic value there), reported rather than dropped.
h Backward compatible? (maintainer-approved exception only) Yes, and no exception is needed. No setting default changes (the src/ diff is 1 file, +1 line), so no SettingsChangesHistory.cpp entry is owed. No on-disk format change: all three consumers of the hash are in-memory caches, and serialization.json persists the field, never a hash of it, so no upgrade or downgrade path is required. Parts already written inconsistently on an affected server stay inconsistent; the fix stops new ones being produced.
i Invariants and contracts preserved? The change can only make the key more injective, i.e. split one pool entry into two, never merge two into one. Equality semantics are untouched (the field was already compared), so no container's key contract changes. One additional hash.update on an existing SipHash inside a const method: no locking, lifetime, allocation or error path is affected, and there is no early-return or failure path to consider.

Session id: cron:clickhouse-review-slot-48:20260805-144700

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @antonio2368, could you review this? SerializationInfoSettings::updateHash omitted map_serialization_version, and that hash is the sole key of the SerializationDynamic pool (no key-equality check on a hit), so a table declaring with_buckets could reuse a basic-configured object, write the plain Array(Tuple) streams, and still record with_buckets in serialization.json; reading that part later asks for the missing .buckets_info stream and raises a logical error.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5ea0dba]

Summary: ✅


AI Review

Summary

This PR fixes the missing map_serialization_version component in the pooled SerializationDynamic cache key and adds an end-to-end stateless reproducer for the bad write/read cycle. The change does prevent new inconsistent Dynamic/Map parts from being written, but I found one remaining contract gap: the current reader path still throws on parts that were already written inconsistently before this patch, so the PR as written does not fully satisfy its “fixes reading” claim.

Findings

⚠️ Majors

  • [src/DataTypes/Serializations/SerializationInfoSettings.cpp:79] Adding the missing hash field only fixes future pool identity. Already-written parts whose serialization.json says with_buckets but whose streams were written in the basic layout still fail in the current code path: SerializationMap::deserializeBinaryBulkStatePrefix goes down the bucketed branch, and MergeTreeReaderWide::getStream still raises LOGICAL_ERROR when ...buckets_info is absent. Suggested fix: either add a compatibility/recovery read path for these legacy bad parts, or narrow the PR contract/changelog to say that this change prevents writing new inconsistent parts rather than fixing reads of existing ones.
Missing context / blind spots
  • ⚠️ Full PR CI is not finished yet (PR and Build (arm_tidy) are still pending), so this review could not use a completed CI signal to validate the final head.
Final Verdict

⚠️ Changes requested

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 5/5 (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 Aug 5, 2026
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d528e52

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
Stress test (amd_tsan) / Test script failed infra: job-level exit code 1 while every durability gate in the same job is green (Test script exit code, Server successfully started, No lost s3 keys, No SharedMergeTree lost forever all OK across 10 server runs); no crash or sanitizer signature is captured a fix task is moved to pending (investigating at full effort - fixing-PR link to follow on this PR)
Build (arm_release) / Post Hooks infra: build_profile_hook.py telemetry INSERT rejected with LogCluster query failed with code 500 after the build succeeded #113409 (external, open)

All 174 check-runs completed and Finish Workflow succeeded. The Test script failed signature is
not specific to this change: over 30 days it spans 126 rows across 96 distinct pull requests and 11
stress flavours, with 7 rows on master.

Session id: cron:our-pr-ci-monitor:20260805-230000

@@ -0,0 +1,61 @@
#include <Core/MergeTreeSerializationEnums.h>

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.

@groeneai remove the gtest as there is a sql test

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed in 5d6b548. I checked the SQL test does not lose anything first: reverting the one-line fix makes 04753 fail on both sides on its own, printing bucketed streams 0 0 0 for the write side and then aborting on the read with the same .buckets_info ... is not found message as the CI reports.

@@ -74,6 +74,7 @@ void SerializationInfoSettings::updateHash(SipHash & hash) const
hash.update(static_cast<int>(version));

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.

@Avogar one line code review

@PedroTadim PedroTadim self-assigned this Aug 10, 2026
The stateless test 04753_dynamic_map_buckets_pooled_serialization already
covers the defect in both directions. Verified by reverting the one-line fix:
the .sql alone reddens twice over, printing "bucketed streams 0 0 0" for the
write side and then aborting on the read side with the byte-identical message
from the CI reports.

The pooled-object behaviour the gtest asserted is reachable from SQL too:
SerializationObjectPool::getOrCreate accounts every insertion in the
SerializationCacheCount metric, so a table declaring with_buckets adds one
entry next to an existing basic one, while a further table with identical
settings adds none. No assertion is lost with the file.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5d6b548

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.

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan) / Logical error: Found patch part ... intersects mutation with version (STID 2781-51e9) trunk bug, not caused by this PR (diff is SerializationInfoSettings.cpp plus its own test) #113998 (mine, open)
Stress test (arm_asan_ubsan) / Cannot start clickhouse-server, Check failed fallout of the same abort above, not an independent failure: fatal.log shows the STID 2781-51e9 assertion killing the server first #113998 (mine, open)
Stress test (arm_tsan) / Logical error: Bad cast from type DB::ColumnString to DB::ColumnNullable (STID 4256-3fc1) trunk bug in the Nested member subcolumn read path #113925 (mine, merged 2026-08-10 10:09Z; this run predates it, so it is picked up on the next push)

Two notes on what is deliberately not listed. Build (arm_release) / Post Hooks has a CIDB
FAIL row but the check itself concludes success on GitHub; it is bookkeeping noise present
on 815 PRs and 241 master runs in the last 7 days, so it is not a failure of this PR. The run
is genuinely finished with coverage: 175 jobs, 155 OK, 18 skipped, 2 failing, and 0 dropped in
the praktika report.

Session id: cron:our-pr-ci-monitor:20260810-150000

hash.update(static_cast<int>(version));
hash.update(static_cast<int>(string_serialization_version));
hash.update(static_cast<int>(nullable_serialization_version));
hash.update(static_cast<int>(map_serialization_version));

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.

This fixes the pool key for future SerializationDynamic objects, but it does not make already-written inconsistent parts readable. If a part already has serialization.json saying map_serialization_version = with_buckets while its streams were written in the basic layout, the fixed build still takes the WITH_BUCKETS branch in SerializationMap::deserializeBinaryBulkStatePrefix and immediately asks the reader for ...buckets_info; MergeTreeReaderWide::getStream still throws the same LOGICAL_ERROR when that stream is absent.

Since this PR closes #113914 as a read-path bug, I think the user-facing fix is still incomplete. Either add a compatibility/recovery path for these legacy bad parts (the reader already has check_stream_exists_callback / actual stream presence to distinguish them) or narrow the PR contract to “prevents writing new inconsistent parts” instead of claiming that the read failure itself is fixed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and I checked it rather than reasoning about it. I built the bad part with a pre-fix binary and read it with the fixed one: it still raises Stream y.Map%28UInt64%2C%20UInt64%29.buckets_info for column y with type Dynamic(max_types=128) is not found. Two things are worse than stated: ALTER TABLE ... MODIFY SETTING map_serialization_version = 'basic' does not help, because the read follows the part's own serialization.json, and OPTIMIZE TABLE ... FINAL aborts too, so the part cannot be rewritten either. It also needs only one table, via the documented map_serialization_version = 'with_buckets' plus map_serialization_version_for_zero_level_parts = 'basic' pair.

I took your first option: the contract is narrowed. The changelog entry and description now say this stops the inconsistent part from being written and that parts written by an earlier version stay unreadable and have to be dropped. I kept Closes #113914, since that issue's own reproducer passes with the fix.

I am not adding the recovery path here. Falling back to the basic layout when .buckets_info is absent would make the reader ignore the part's declared version, which is branched on at 15 sites across the 4 Map serialization classes, and it would also silently accept a genuinely truncated bucketed part, which is the case this error currently catches. That is a read-path compatibility decision worth its own PR, not an addition to a one-line cache-key fix.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5ea0dba

CI is fully finished on this head and there are no failures to own: praktika reports
top-level OK with 157 jobs green and 18 skipped, every skip carrying an explicit reason
(reused from cache, Not affected by the changed files and not required, not labeled with 'pr-performance', and so on), and no dropped job. Finish Workflow is success.

Check / test Reason Owner / fixing PR
(none) no failing test on this head n/a
Sync - CH Inc sync (private, not actionable)

Build (arm_release) / Post Hooks appears as a row in the CI database, but that check's
own conclusion is success, so it is bookkeeping noise rather than a failure line. The three
Stress test reds visible in the database for this PR belong to the previous head
5d6b548a023c, which is already covered by the ledger above this one.

Session id: cron:our-pr-ci-monitor:20260811-000000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 11, 2026
Merged via the queue into ClickHouse:master with commit 57b9bc5 Aug 11, 2026
181 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 Aug 11, 2026
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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

4 participants