Skip to content

Fix potential use-after-free when reading String .size or several Variant subcolumns over discontinuous ranges - #109458

Closed
tiandiwonder wants to merge 5 commits into
masterfrom
fix-cow-shared-deserialize-state
Closed

tiandiwonder wants to merge 5 commits into
masterfrom
fix-cow-shared-deserialize-state

Conversation

@tiandiwonder

Copy link
Copy Markdown
Contributor

Related: #109020

Problem. When a query reads a String column together with its .size subcolumn (with the legacy single_stream serialization), or reads several subcolumns of the same Variant column (elements, or an element together with a null map), and the primary key selects discontinuous mark ranges, an internal column buffer shared between the subcolumn readers is appended to in place while another reader still references it. If the append reallocates the buffer, the other holder is left pointing at freed memory — a latent use-after-free of the same class as the recurring arm_asan_ubsan double-free / allocator-CHECK crashes addressed by #109020.

Root cause. Deserialization of the String .size subcolumn (SerializationStringSize::deserializeWithStringData) and of Variant element / element-null-map subcolumns (SerializationVariantElement, SerializationVariantElementNullMap) keeps a partially read column in the per-column deserialize state so it survives across readRows calls, and also publishes that column into the substreams cache. A second consumer of the same substream in the same query picks the column up from the cache and keeps a reference to the very same object. When one block spans several readRows calls (continue_reading accumulation over discontinuous mark ranges), the next cache-miss read appends to the shared column in place through assumeMutable, which ignores the reference count and so violates the COW contract. Confirmed at runtime with temporary use_count instrumentation: all three sites append with use_count == 2 on the added regression tests before the fix, and reach zero violations with identical query results after it.

Fix. Go through IColumn::mutate(std::move(...)) before the in-place append: a shared column is cloned first (the other holder keeps its frozen snapshot), while an exclusively owned column is still appended in place, so the zero-copy path is preserved. For the Variant sites the mutate is placed before the discriminator-mode branch so both BASIC and COMPACT modes append into an exclusively owned column. This is the same pattern as #109020, which fixes the same defect class for the with_size_stream .size read paths; the two PRs touch disjoint code and do not depend on each other. Regression tests 04499_string_size_subcolumn_single_stream_shared_state and 04500_variant_element_discriminators_shared_state pin the correct results on all builds and give ASan builds the discontinuous-ranges recipe that exercises the shared-buffer path.

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 a potential use-after-free when a query reads a String column together with its .size subcolumn, or several subcolumns of the same Variant column, over discontinuous ranges of a table: an internal buffer shared between the subcolumn readers could be reallocated in place while still referenced.

…states

Deserialization of the String .size subcolumn (single_stream format) and
of Variant element / element-null-map subcolumns keeps a partially read
column in the deserialize state and also publishes it into the
substreams cache, where a second consumer of the same substream in the
same query (the emitted full String column, or the state of another
subcolumn of the same Variant) keeps a reference to the very same
object. When one block spans several readRows calls (discontinuous mark
ranges selected by the primary key), the next cache-miss read appended
to the shared column in place via assumeMutable, violating the COW
contract; if the append reallocated the buffer, other holders could be
left reading freed memory (observable as use-after-free under ASan).

Go through IColumn::mutate before the append so a shared column is
cloned first, while an exclusively owned column is still appended in
place (the zero-copy path is preserved). Same pattern as #109020, which
fixes the same defect class for the with_size_stream .size read paths.

Confirmed at runtime with temporary use_count instrumentation: all three
sites appended with use_count == 2 on the added tests before the fix,
and zero violations with identical query results after it.

Related: #109020

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [123a208]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_tsan, 3/6) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL

AI Review

Summary

This PR closes the shared-state COW holes in the legacy single_stream String .size reader and in Variant discriminator subcolumn reads across discontinuous ranges, and the new regressions cover the touched single_stream and Variant paths. I cannot approve it yet because the with_size_stream String reader still appends to a cached/shared size column in place, so the advertised String + .size fix is still incomplete.

Findings
  • ❌ [src/DataTypes/Serializations/SerializationStringSize.cpp:143] This only fixes the legacy single_stream .size reader. SerializationString::deserializeBinaryBulkWithSizeStream still stores string_state->size_column in deserialize state, publishes that same ColumnUInt64 into the substreams cache, and later appends to it through assumeMutable at src/DataTypes/Serializations/SerializationString.cpp:824-829. If the query also reads s.size, the .size reader can reuse that cached column as its result, so the next discontinuous-range readRows still reallocates a buffer another reader holds. Mirror the IColumn::mutate there and add a focused with_size_stream regression; the same 04499 shape should reproduce it.
Final Verdict

Status: ⚠️ Request changes

Mirror the COW break in SerializationString::deserializeBinaryBulkWithSizeStream and add a with_size_stream regression before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 6, 2026
@tiandiwonder
tiandiwonder requested a review from Avogar July 6, 2026 01:15
@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label Jul 6, 2026

@alexey-milovidov alexey-milovidov left a comment

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.

Thanks, this is amazing!

I tried to find more cases of assumeMutable, that we should avoid if we can.
Because COWPtr was designed to prevent exactly this type of errors.

@alexey-milovidov alexey-milovidov self-assigned this Jul 6, 2026
… deserialization

`SerializationVariantElementNullMap::deserializeBinaryBulkWithMultipleStreams`
used `num_read_discriminators` before subtracting `rows_offset`. In the
compact-discriminator path `deserializeCompactDiscriminators` appends
`rows_offset + limit` discriminators but reports `variant_limit` only for the
post-offset range, so the `variant_limit == 0` fast path filled
`num_read_discriminators` (= `rows_offset + limit`) entries into the null map
instead of just `limit`, over-growing `v.<type>.null` when a range with a
skipped prefix contains no rows of this variant.

Mirror `SerializationVariantElement`, which already normalizes with
`discriminators_offset += rows_offset; num_read_discriminators -= rows_offset;`
before its fast paths, so both the `variant_limit == 0` and
`variant_limit == num_read_discriminators` branches append the correct
post-offset count.

Addresses the `clickhouse-gh` review finding on this PR.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed af38024 addressing the clickhouse-gh finding on SerializationVariantElementNullMap.cpp.

Fix. SerializationVariantElementNullMap::deserializeBinaryBulkWithMultipleStreams now normalizes with discriminators_offset += rows_offset; num_read_discriminators -= rows_offset; before the fast paths, exactly as SerializationVariantElement already does. Previously the variant_limit == 0 fast path filled num_read_discriminators (= rows_offset + limit in the compact-discriminator path) entries instead of limit, over-growing v.<type>.null when a range with a skipped prefix contains no rows of this variant.

On a regression test. I could not construct a deterministic SQL test for this, because the buggy path is currently unreachable: rows_offset is passed as 0 by every IMergeTreeReader::readRows call site I can find in the read pipeline. MergeTreeRangeReader::DelayedStream skips a leading offset by read-and-discard and hardcodes rows_offset = 0 (MergeTreeRangeReader.cpp:168), IMergeTreeDataPart passes 0, and MergeTreeReaderTextIndex forwards its own rows_offset to the fallback reader, which is itself 0 (it is invoked through DelayedStream). So deserializeBinaryBulkWithMultipleStreams never sees rows_offset > 0 and the fast path cannot fire on a skipped-prefix range. I also checked empirically (text index on v.String + LIKE fallback + compact discriminators + discontinuous ranges → correct results). The rows_offset parameter is wired through the readers but not yet driven non-zero by any caller, which is why SerializationVariantElement handles it defensively; this change keeps the null-map path consistent with it. The existing 04500_variant_element_discriminators_shared_state test already covers the compact null-map path (with rows_offset = 0).

On new_tests_check. The gate is red because the three regression tests reproduce the use-after-free only under ASan; the per-arch Bugfix Validation jobs run non-ASan builds, so the tests pass on master HEAD there and no arch can XFAIL-validate them. This is the same situation as #109020 (same defect class). Since this is a genuine bug fix, clearing the gate likely needs a maintainer decision (reclassify the changelog category or override the gate) rather than an additional test.

Mirror the `IColumn::mutate` fix from `SerializationVariantElement` in
`SerializationVariant::deserializeBinaryBulkWithMultipleStreams`.

When the full `Variant` column is read before one of its subcolumns
(e.g. `SELECT v, v.UInt64`), the full-column reader puts its local
discriminators into the substreams cache as is, and the subcolumn reader
adopts the very same column from the cache. The subcolumn deserialize
state then keeps that shared discriminators column across `readRows`
calls, so a later discontinuous range that appends to it in place via
`assumeMutable` reallocates the buffer still referenced by the subcolumn
state — the same use-after-free class this PR fixes for the
subcolumn-owned side.

Go through `IColumn::mutate` before deserializing discriminators so a
shared column is cloned first; it is a no-op when the column is not
shared. Extends the `04500` regression test to read the full `Variant`
together with an extracted element and null-map subcolumn over
discontinuous ranges.

Addresses the `clickhouse-gh` review finding on
`SerializationVariant.cpp`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed f4f8680 addressing the clickhouse-gh finding on SerializationVariant.cpp.

Fix. SerializationVariant::deserializeBinaryBulkWithMultipleStreams now goes through IColumn::mutate on col.getLocalDiscriminatorsPtr() before deserializing discriminators, mirroring the fix already applied to SerializationVariantElement. When the full Variant column is read before one of its subcolumns, the full-column reader puts its local discriminators into the substreams cache as is (discriminators_for_cache = col.getLocalDiscriminatorsPtr() when rows_offset == 0), and the subcolumn reader adopts the same column from the cache (std::tie(variant_element_state->discriminators, num_read_discriminators) = *cached_column_with_num_read_rows). The subcolumn state then keeps that shared column across readRows calls, so a later discontinuous range that appends to it in place via assumeMutable (BASIC path) or deserializeCompactDiscriminators (COMPACT path) would reallocate the buffer still referenced by the subcolumn state — the same use-after-free class as the subcolumn-owned side. IColumn::mutate clones the shared column first and is a no-op when the discriminators are not shared (the common full-column-only read).

Test. Extended 04500_variant_element_discriminators_shared_state to read the full Variant together with an extracted element (v.UInt64) and null-map (v.String.null) subcolumn over the same discontinuous ranges, for both BASIC and COMPACT modes. Reading toString(v) forces the full-column reader to run alongside the subcolumn reader (optimize_functions_to_subcolumns = 0), so they share the discriminators through the cache. Results verified against a non-sanitized build.

@Avogar Avogar self-assigned this Jul 6, 2026
/// The column in the state may still be shared with the full column emitted as a result
/// of a previous read through the substreams cache. Go through IColumn::mutate so a shared
/// column is cloned before we append to it in place.
auto mutable_string_column = IColumn::mutate(std::move(string_state.column));

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 legacy single_stream .size reader, but the with_size_stream path still has the same aliasing hole.

SerializationString::deserializeBinaryBulkWithSizeStream keeps string_state->size_column in deserialize state, publishes that exact column into the substreams cache, and then appends to it in place on the next cache-miss readRows pass via *string_state->size_column->assumeMutable() at src/DataTypes/Serializations/SerializationString.cpp:824-829. If the same query also reads s.size, SerializationStringSize::deserializeBinaryBulkWithSizeStream can take that cached size_column as its result column, so a discontinuous-range read still reallocates a buffer another reader is holding.

That leaves the String + .size fix incomplete for string_serialization_version = 'with_size_stream' (and for any nested String path, such as Variant(String, ...), that goes through the same reader). Please mirror the IColumn::mutate before the append in SerializationString::deserializeBinaryBulkWithSizeStream and add a with_size_stream regression alongside 04499.

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.

This site is intentionally out of scope for this PR: the open PR #109020 fixes exactly this path — it puts IColumn::mutate before the append in SerializationString::deserializeBinaryBulkWithSizeStream and in the with_size_stream branch of SerializationStringSize::deserializeBinaryBulkWithSizeStream, with its own regression test 04409_string_size_subcolumn_shared_buffer_merge. As noted in the description, this PR covers the disjoint legacy single_stream and Variant sites, so the two PRs complement each other without conflicting.

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 79.80% 85.80% +6.00%
Functions 91.70% 92.70% +1.00%
Branches 72.00% 78.00% +6.00%

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

Full report · Diff report

@Avogar Avogar left a comment

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.

This is something strange tbh. The whole point in substreams cache in serializations is to share the same subcolumn in multiple deserialized columns and fill it only once using assumeMutable so all shared copies will see updates. All MergeTree readers return constant ColumnPtr columns with possible shared subcolumns between columns, which is totally fine and never led to any issues. So the fix looks wrong.

Also tests don't reproduce anything uder asan build.

@tiandiwonder

Copy link
Copy Markdown
Contributor Author

So the fix looks wrong.

Thanks for the verification. I will close it and would you please check #109020?

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants