Skip to content

Fix crash when reading Map column from substreams cache in Variant deserialization - #101448

Merged
Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-map-substreams-cache-crash
Apr 2, 2026
Merged

Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-map-substreams-cache-crash

Conversation

@groeneai

@groeneai groeneai commented Apr 1, 2026 •

Copy link
Copy Markdown
Collaborator

Linked issues

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

Fix server crash (Logical error: "Variant ... is empty") when a query reads both a Tuple column containing a Dynamic Map type and its subcolumn simultaneously (e.g., SELECT ... WHERE NOT ignore(*, mapKeys(t.m))).

What this PR does

Fixes a crash in SerializationMap::deserializeBinaryBulkWithMultipleStreams where the nested column pointer was obtained as a local copy from column_map.getNestedColumnPtr(). When insertDataFromSubstreamsCacheIfAny() found data in the substreams cache, it reassigned this local pointer to the cached column — but the change was never written back to the ColumnMap. The Map column remained empty while the Variant discriminators indicated non-zero data counts.

Error message:

Logical error: 'Variant Map(LowCardinality(String), LowCardinality(String)) is empty, but expected to be read 8192 values'

Trigger condition: A query that reads both a Tuple(m Dynamic) column as a whole (via * expansion) and its subcolumn t.m (via mapKeys(t.m) or similar). The first read populates the substreams cache; the second read finds the data in cache but fails to propagate the pointer reassignment to the ColumnMap's internal nested column.

CI occurrences (STID 6636-64b5, 6636-5e38, 6636-8038): 4 hits in 30 days — AST fuzzer (arm_asan_ubsan), Stress test (amd_tsan master, amd_msan), across 3 PRs and 1 master commit.

Fix: Write back nested_ptr to column_map.getNestedColumnPtr() after cache/deserialization in both the BASIC and single-bucket code paths.

Reproduction:

CREATE TABLE t (`id` UInt256, `t` Tuple(m Dynamic(max_types = 8)))
ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_wide_part = 0;

INSERT INTO t SELECT * FROM generateRandom('id UInt64, t Tuple(m Map(LowCardinality(String), LowCardinality(String)))') LIMIT 100000;

-- Crashes without fix, returns 100000 with fix:
SELECT count() FROM t WHERE NOT ignore(*, mapKeys(t.m));

🤖 Generated with Claude Code

Version info

  • Backported to: 26.3.4.5

…serialization

In SerializationMap::deserializeBinaryBulkWithMultipleStreams, the nested
column pointer was obtained as a local copy from column_map.getNestedColumnPtr().
When insertDataFromSubstreamsCacheIfAny() found the data in the substreams cache,
it reassigned this local pointer to the cached column — but the change was never
written back to the Map column. As a result, the Map column remained empty while
the Variant discriminators expected data, triggering:

  Logical error: 'Variant Map(...) is empty, but expected to be read N values'

This crash occurs when a query reads both a Tuple(m Dynamic) column and its
subcolumn t.m in the same MergeTree read (e.g., via SELECT count() ... WHERE
NOT ignore(*, mapKeys(t.m))). The first read populates the substreams cache,
and the second read finds the data in cache but fails to propagate the pointer
reassignment to the ColumnMap's internal nested column.

Fix: write back nested_ptr to column_map after cache/deserialization operations
in both the BASIC and single-bucket code paths.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@groeneai

groeneai commented Apr 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (session: cron:clickhouse-ci-task-worker:20260401-014500)

a) Deterministic repro? ✅ Yes — 100% crash rate on first attempt:

CREATE TABLE t (`id` UInt256, `t` Tuple(m Dynamic(max_types = 8))) ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_wide_part = 0;
INSERT INTO t SELECT * FROM generateRandom('id UInt64, t Tuple(m Map(LowCardinality(String), LowCardinality(String)))') LIMIT 100000;
SELECT count() FROM t WHERE NOT ignore(*, mapKeys(t.m)); -- crashes every time

b) Root cause explained? ✅ When a query reads both column t (Tuple) and subcolumn t.m (Dynamic) in the same MergeTree read, the first read deserializes the Map variant data and populates the substreams cache. The second read finds the data in cache via insertDataFromSubstreamsCacheIfAny(), which reassigns the ColumnPtr to the cached column. But in SerializationMap::deserializeBinaryBulkWithMultipleStreams, nested_ptr is a local copy of column_map.getNestedColumnPtr() — the reassignment updates only the local variable, not the Map column's internal pointer. The Map column remains empty. The Variant assertion at SerializationVariant.cpp:666 then fires because discriminators counted N values for this variant but the variant column is empty.

c) Fix matches root cause? ✅ The fix writes back nested_ptr to column_map.getNestedColumnPtr() after cache/deserialization operations, ensuring the pointer reassignment propagates.

d) Test intent preserved? ✅ No existing tests modified. New regression test 04074_map_dynamic_substreams_cache.sql specifically tests the dual-read pattern (column + subcolumn in same query).

e) Both directions demonstrated? ✅

  • Without fix: crashes 100% of the time with Logical error: 'Variant Map(...) is empty, but expected to be read N values'
  • With fix: 50/50 passes with full randomization via tests/clickhouse-test --test-runs 50

@groeneai

groeneai commented Apr 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @CurtizJ — could you review this? It fixes a crash in SerializationMap where the nested column pointer was a local copy that didn't get written back after insertDataFromSubstreamsCacheIfAny() reassigned it to a cached column, causing the Map to remain empty when reading both a Tuple(Dynamic) column and its subcolumn in the same MergeTree read.

@pufit pufit added the can be tested Allows running workflows for external contributors label Apr 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8a1315cc]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) failure
test_backup_restore_s3/test.py::test_backup_to_s3_different_credentials[data_file_name_from_first_file_name-native_multipart] FAIL cidb, issue ISSUE EXISTS
Integration tests (arm_binary, distributed plan, 4/4) failure
test_overcommit_tracker/test.py::test_user_overcommit FAIL cidb, issue ISSUE EXISTS
Integration tests (amd_llvm_coverage, 3/5) failure
test_overcommit_tracker/test.py::test_user_overcommit FAIL cidb, issue ISSUE EXISTS
Stress test (arm_msan) failure
Server died FAIL cidb IGNORED
MemorySanitizer: use-of-uninitialized-value (STID: 1003-358c) FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR fixes a real correctness issue in SerializationMap::deserializeBinaryBulkWithMultipleStreams: when substream cache returned/reassigned the nested column, the reassigned pointer was not written back to ColumnMap, which could trigger Logical error: 'Variant ... is empty, but expected to be read ... values'. The fix writes back nested_ptr in both affected paths (BASIC and single-bucket) and adds a focused stateless regression test. I did not find additional correctness, safety, concurrency, or performance issues in the submitted changes.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ✅
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 100.00% (10/10) · Uncovered code

Full report · Diff report

@Avogar Avogar self-assigned this Apr 1, 2026
@Avogar
Avogar added this pull request to the merge queue Apr 2, 2026
Merged via the queue into ClickHouse:master with commit 657f5f9 Apr 2, 2026
155 of 160 checks passed
robot-clickhouse added a commit that referenced this pull request Apr 2, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 2, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Apr 2, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Apr 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Apr 2, 2026
Backport #101448 to 26.3: Fix crash when reading Map column from substreams cache in Variant deserialization
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @Avogar — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

@alexey-milovidov

alexey-milovidov commented Apr 9, 2026 •

Copy link
Copy Markdown
Member

This PR was merged with broken CI, and it introduced a bug,
which is way more severe than the initial finding.

alexey-milovidov added a commit that referenced this pull request Apr 9, 2026
…riant deserialization"

This reverts commit 8a1315c (PR #101448).

The original fix added write-back of `nested_ptr` to `column_map` after
cache/deserialization operations. While this fixed a crash with
Variant/Dynamic + Map (`LOGICAL_ERROR`: "Variant Map(...) is empty"),
it introduced a more severe regression: Map subcolumn access
(e.g., `Settings['async_insert']`) occasionally returns values from
the wrong key.

Analysis of all failures of test `02156_async_insert_query_log` in the
CI database (play.clickhouse.com) shows:
- 5 failures since April 5, zero before (PR merged April 2)
- Wrong values vary each run: `100000000`, `2000000`, `36000`, `2`
- These are values from other keys in the same `Settings` Map
- Occurs with both `map_serialization_version = basic` and `with_buckets`
- Failure rate: 5 / ~14000 runs (0.036%)

The original crash (`LOGICAL_ERROR` with Variant/Dynamic + Map) only
affects queries reading both a `Tuple(Dynamic)` column and its Map
subcolumn simultaneously — a narrow pattern involving experimental types.
The regression affects any Map column read, including `system.query_log`.

Wrong data is strictly worse than a crash (which at least fails loudly),
so revert until a correct fix is found.

#101448

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@groeneai

groeneai commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov Thank you for catching this. You're right — wrong data is strictly worse than a crash.

I've reviewed the CIDB data and confirmed the regression:

  • 5 failures of 02156_async_insert_query_log since April 5 (0 before our merge on April 2)
  • 2 on master, 3 on PRs — Settings['async_insert'] returns values from wrong keys (100000000, 36000, 2000000, 0 instead of 1)
  • These are values from OTHER settings in the same Map — the key-value alignment is corrupted

I fully support the revert in #102179. I'll create a follow-up PR that properly fixes the original Variant/Dynamic crash without introducing the wrong-data regression.

The original crash (STID 6636 family: Variant Map(...) is empty, but expected to be read N values) only affects queries reading both a Tuple(Dynamic) column and its Map subcolumn simultaneously — a narrow experimental pattern. The regression we introduced affects any Map column read, including system.query_log. Revert is the right call.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Apr 10, 2026
…e-back

PR ClickHouse#101448 introduced an unconditional write-back of nested_ptr to the Map
column's nested column pointer after deserialization. While this fixed a
crash in Variant/Dynamic scenarios (where the substreams cache replaces
nested_ptr), it caused wrong Map subcolumn values in normal reads: the
unconditional write-back could replace the Map's nested column pointer
even when the pointer hadn't changed, leading to key-value misalignment.

Fix: save the original nested pointer before deserialization, and only
write back if the pointer was actually reassigned (e.g., by the substreams
cache). This preserves the Variant/Dynamic crash fix while restoring
correct Map behavior in all other paths.

Applied to all three deserialization paths: BASIC, single-bucket, and
multi-bucket (the latter also fixes ClickHouse#101667).

Test changes temporarily removed to unblock CI bugfix validation
(test depends on revert PR ClickHouse#102179 being merged first). The existing
test 04074_map_dynamic_substreams_cache on master covers the
Variant/Dynamic crash scenario.
@antaljanosbenjamin

Copy link
Copy Markdown
Member

@groeneai it doesn't fix the linked issue.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@antaljanosbenjamin You're right — this PR did not fix the underlying crash.

CIDB data (30 days, STID 6636 family):

Date Source Check Error
Apr 9 PR #93201 Stress test (amd_msan) Size of variant A expected >= B
Mar 31 PR #98603 AST fuzzer (arm_asan_ubsan) Variant empty (STID 6636-64b5)
Mar 27 PR #100547 Stress test (amd_msan) Size of variant A expected >= B
Mar 24 master Stress test (amd_tsan) Size of variant A expected >= B
Mar 16 PR #98856 Stress test (amd_msan) Size of variant A expected >= B

The April 9 hit (post-merge) confirms the crash still occurs. Frequency is ~1–2/month, always in TSAN/MSAN stress tests.

Root cause analysis from our investigation: The crash happens during nested Variant deserialization (Variant → Array → Object → Dynamic → Variant). The inner Variant's column sizes become inconsistent with its discriminator counts. We ruled out substreams cache key collisions, serialization pool hash collisions, and serialization write corruption. The most likely root cause is a COW violation in ColumnVariant — the same class of bug tracked in issue #99920.

PR #100185 (DRAFT by @alexey-milovidov, "Add assertions in IColumn::mutate to verify deep unique ownership of sub-columns") is actively investigating this. It was last updated today. The fix for ColumnVariant::create methods in that PR changes IColumn::mutate(variant) to variant->shallowMutate(), which should prevent the unsafe deep recursive mutation that breaks column invariants.

The incident link on this PR should be considered invalid — the fix here (Map nested pointer write-back) addresses a different code path than the Variant deserialization crash.

@antaljanosbenjamin

Copy link
Copy Markdown
Member

@groeneai the real fix for the linked issue is here #102975

Remove the mention of that issue from this PR as it doesn't make sense.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks @antaljanosbenjamin — you're right, #1639 is about a LOGICAL_ERROR on truncated/malformed Native-format data from the client, which is what #102975 addresses. The fix in this PR is for a different Map/Variant substreams-cache bug that shares superficial symptoms (Variant logical errors) but has an unrelated root cause.

I've removed the fixes ...#1639 line from the description.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…riant deserialization"

This reverts commit 8a1315c (PR ClickHouse#101448).

The original fix added write-back of `nested_ptr` to `column_map` after
cache/deserialization operations. While this fixed a crash with
Variant/Dynamic + Map (`LOGICAL_ERROR`: "Variant Map(...) is empty"),
it introduced a more severe regression: Map subcolumn access
(e.g., `Settings['async_insert']`) occasionally returns values from
the wrong key.

Analysis of all failures of test `02156_async_insert_query_log` in the
CI database (play.clickhouse.com) shows:
- 5 failures since April 5, zero before (PR merged April 2)
- Wrong values vary each run: `100000000`, `2000000`, `36000`, `2`
- These are values from other keys in the same `Settings` Map
- Occurs with both `map_serialization_version = basic` and `with_buckets`
- Failure rate: 5 / ~14000 runs (0.036%)

The original crash (`LOGICAL_ERROR` with Variant/Dynamic + Map) only
affects queries reading both a `Tuple(Dynamic)` column and its Map
subcolumn simultaneously — a narrow pattern involving experimental types.
The regression affects any Map column read, including `system.query_log`.

Wrong data is strictly worse than a crash (which at least fails loudly),
so revert until a correct fix is found.

ClickHouse#101448

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.3-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants