Skip to content

Revert "Extend COW-safe IColumn::mutate sweep to deserialize and patch-apply paths" - #110434

Closed
Avogar wants to merge 1 commit into
masterfrom
revert-109105-cow-safe-merge-read-deserialize-double-free
Closed

Avogar wants to merge 1 commit into
masterfrom
revert-109105-cow-safe-merge-read-deserialize-double-free

Conversation

@Avogar

@Avogar Avogar commented Jul 14, 2026

Copy link
Copy Markdown
Member

Reverts #109105

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [422d9d1]


AI Review

Summary

This PR reverts the recent IColumn::mutate hardening for deserialization paths. I do not think the revert is safe as-is: it restores rows_offset > 0 cache-hit mutations that can append to and compact a column while the substreams cache still references the same storage, which reopens the same memory-safety regressions the reverted change was addressing. The PR should not merge in its current form.

Findings

❌ Blockers

  • [src/DataTypes/Serializations/SerializationArrayOffsets.cpp:41, src/DataTypes/Serializations/SerializationStringSize.cpp:221] The rows_offset > 0 cache-hit branches append cached size data into column through assumeMutable, then compact that same ColumnUInt64 in place. A prior rows_offset == 0 read stores column itself in the substreams cache, so the later partial-granule read can mutate storage that the cache still owns, which is exactly the heap-use-after-free / double-free class of bug the reverted hardening fixed.
    Suggested fix: restore the clone-if-shared step before the append/compaction, e.g. via IColumn::mutate.

  • [src/DataTypes/Serializations/SerializationVariant.cpp:564] The discriminator cache-hit path has the same aliasing problem: the fresh-read path caches col.getLocalDiscriminatorsPtr() itself when rows_offset == 0, so a later partial-granule read appends to and compacts discriminators that are still referenced from the cache. Deleting 04504_variant_discriminators_cow_safe_rows_offset removes the regression test that was covering this exact path, so the revert reintroduces a known memory-safety hole rather than just an optimization.
    Suggested fix: keep the discriminator column COW-safe on cache hits and preserve a focused regression test for this rows_offset scenario.

Final Verdict

Status: ❌ Block

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 14, 2026
@alexey-milovidov alexey-milovidov self-assigned this Jul 14, 2026
@alexey-milovidov

alexey-milovidov commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

@Avogar, hold on.

We have occasional bugs due to shared modification of columns that were shared with assumeMutable.
I am the author of COWPtr and its mechanics, and I designed it in a way that you almost never should use assumeMutable.

assumeMutable is the same as unsafe in Rust - never appreciated.

The IColumn::mutate does not do an extra copy if a column is not shared. And if a column is shared, it is either a bug or convoluted code.

I need this change to be more confident in #96844

Also, I very much dislike the amount of assumeMutable and whatever-serialization-stream-cache introduced. It makes the code difficult to reason about and bug-prone.

@alexey-milovidov

Copy link
Copy Markdown
Member

If you see performance is worse in some cases, please add performance tests to prove that.

@alexey-milovidov

alexey-milovidov commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

I recommend fixing bugs first and only then thinking about performance. If the substream cache is bad, it will be removed.

#109458
#109090
#109020
#100185
#102179
#102187

@alexey-milovidov

alexey-milovidov commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

See also this:

#107457
#107374
#25454
#4851

The amount of bugs we have due to a reckless usage of assumeMutable, especially in LowCardinality, Variant, Dynamic, JSON is staggering.

mutable_column->insertRangeFrom(*cached_column, cached_column->size() - num_read_rows, num_read_rows);
column = std::move(mutable_column);
}
column->assumeMutable()->insertRangeFrom(*cached_column, cached_column->size() - num_read_rows, num_read_rows);

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 reopens the rows_offset > 0 aliasing bug from the reverted change. When the same size substream is read once with rows_offset == 0, line 63 stores column itself in the cache; a later cache hit in the same range comes back here with cached_column sharing that storage. Appending through assumeMutable and then compacting the offsets in place below mutates the buffer that the cache still owns, which is the same heap-use-after-free / double-free path the COW-safe version was closing.

The identical regression is still present in SerializationStringSize.cpp:221, so this needs a clone-if-shared step (IColumn::mutate or equivalent) before the append.

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.

That's true. This PR is not acceptable.

mutable_discriminators->insertRangeFrom(*cached_column, cached_column->size() - num_read_rows, num_read_rows);
discriminators = std::move(mutable_discriminators);
}
col.getLocalDiscriminatorsPtr()->assumeMutable()->insertRangeFrom(*cached_column, cached_column->size() - num_read_rows, num_read_rows);

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 has the same problem for Variant discriminators. On the fresh-read path below, rows_offset == 0 caches col.getLocalDiscriminatorsPtr() itself, not a cut() copy. A later partial-granule read of the same substream therefore hits this branch with cached_column aliasing the live discriminators, so the assumeMutable append plus the in-place rows_offset compaction later in this function mutate storage that is still referenced by the cache.

04504_variant_discriminators_cow_safe_rows_offset was added to pin exactly this case, so deleting that test together with the COW detachment reintroduces the same heap-use-after-free / double-free regression instead of just removing an extra copy.

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, if this is not true, make the code more understandable, clearer, not only for genius experts but also for stupid creatures like AI agents or me.

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

Not approved. And please don't revert bug fixes.

@alexey-milovidov

Copy link
Copy Markdown
Member

I don't mind if something about Variant/Dynamic/JSON will degrade a little.
We should accept that in favor of memory-safe code.

@Avogar

Avogar commented Jul 14, 2026

Copy link
Copy Markdown
Member Author

If you see performance is worse in some cases, please add performance tests to prove that.

I will add it

And please don't revert bug fixes.

But the test from the "bug fix" doesn't reproduce anything. So the PR didn't fix anything

@alexey-milovidov

alexey-milovidov commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

I'm preparing another PR, it will burn all incorrect usages of COWPtr furiously. Can't wait to see it merged.
#100185

@alexey-milovidov

Copy link
Copy Markdown
Member

And another one: #110471

@Avogar

Avogar commented Jul 15, 2026

Copy link
Copy Markdown
Member Author

But still, that "Bug fix" PR didn't fix anything - the test doesn't reproduce any problems, it means this was not a bug fix, but just a change in existing code that leads to peformance degradation that was unnoticed due to lack of performance tests.

Here is the clear degradation (I made it in a way it clearly shows the difference):

set allow_suspicious_fixed_string_types=1;
create table test (t Tuple(t Tuple(s1 FixedString(1000), s2 FixedString(1000), s3 FixedString(1000), s4 FixedString(1000), s5 FixedString(1000)))) engine=MergeTree order by tuple() settings min_bytes_for_wide_part=1000000000000;
insert into test select tuple(tuple(randomString(1000), randomString(1000), randomString(1000), randomString(1000), randomString(1000))) from numbers(1000000);
optimize table test final;

select t.t, t.t.s1, t.t.s2, t.t.s3, t.t.s4, t.t.s5 from test format Null settings max_threads=1, preferred_block_size_bytes=1000000000000

26.6:

0 rows in set. Elapsed: 2.729 sec. Processed 1.00 million rows, 10.00 GB (366.38 thousand rows/s., 3.66 GB/s.)
Peak memory usage: 979.05 MiB.

master:

0 rows in set. Elapsed: 14.616 sec. Processed 1.00 million rows, 10.00 GB (68.42 thousand rows/s., 684.19 MB/s.)
Peak memory usage: 931.14 MiB.

And this is the flamegraph on 26.6:
flame_cpu_26 6

And this is on master:
flame_cpu_master

You can see that the main overhead is data copy in IColumn::mutate.

I agree that the code with assumeMutable is dangerous and should not be used, but for historical reasons (I actually have no idea why, it was like this long time already) in serializations we propagate constant ColumnPtr to deserialize data into it, which is strange, I think we should operate on MutableColumnPtr here or even plain IColumn & so we work clearly on mutable objects.

If you give me a chance, I can try to refactor this code in a way we will work with mutable objects, so I will get rid of assmueMutable in serializations a tall

@Avogar

Avogar commented Jul 15, 2026 •

Copy link
Copy Markdown
Member Author

However, looking at the code, I start to understand why we use ColumnPtr here. Because MutableColumnPtr is non-copyable. So we won't be able to use substreams cache to share subcolumns between columns.

@Avogar

Avogar commented Jul 15, 2026

Copy link
Copy Markdown
Member Author

So the idea of substreams cache is to avoid copying the data when you read the data from the same stream multiple times (for example, when you read Tuple and its subcolumns, or when different subcolumns share the same stream, like array offsets or variant discriminators). To avoid that we might share the same subcolumns in result columns. It should not lead to any problems because the result of MergeTree reader is a set of constant columns that must not be changed in-place.

@Avogar

Avogar commented Jul 15, 2026

Copy link
Copy Markdown
Member Author

@CurtizJ you may also have a few words to say here

@CurtizJ

CurtizJ commented Jul 16, 2026

Copy link
Copy Markdown
Member

Initially, the substreams cache was introduced to avoid deserializing the same substream twice when a complex column is read together with its subcolumns (null, size0, etc.). It was a generalization of the shared offsets of Nested to other complex data types. The code expected to look like this:

if (auto cached_column = getFromSubstreamsCache(cache, settings.path))
{
    col.getNullMapColumnPtr() = cached_column;
}
else if (auto * stream = settings.getter(settings.path))
{
    DataTypeUInt8().deserializeBinaryBulk(col.getNullMapColumn(), *stream, limit, 0);
    addToSubstreamsCache(cache, settings.path, col.getNullMapColumnPtr());
}

So the invariant was simple: a substream column is mutated by deserialization exactly once per read, and only by the first reader; all other owners share the pointer and never modify it. The sharing was intentional and safe — not elegant, but simple, and it never caused problems.

Now I see that we can append data to the cached column: insertDataFromCachedColumn does assumeMutable()->insertRangeFrom(...) into a column that may itself be shared, which looks dangerous. And the choice between "share the pointer" and "append the rows" is made by non-obvious runtime conditions. This may be the source of memory-safety bugs.

I think the first mode of substream cache is acceptable, and we should keep it. Can we somehow avoid appending to the shared columns, or keep IColumn::mutate only for these paths, and remove it from generic ISerialization::deserializeBinaryBulkWithMultipleStreams?

@Avogar

Avogar commented Jul 16, 2026

Copy link
Copy Markdown
Member Author

I think the first mode of substream cache is acceptable, and we should keep it. Can we somehow avoid appending to the shared columns, or keep IColumn::mutate only for these paths, and remove it from generic ISerialization::deserializeBinaryBulkWithMultipleStreams?

That's exactly what I want to do here: #110714.

@Avogar

Avogar commented Jul 16, 2026

Copy link
Copy Markdown
Member Author

Also, I want to make an experiment PR to change the code of substream cache so it doesn't reuse the same column, but stores the data of the currently deserialized range, so we can copy only this range when we have multiple columns/subcolumns sharing the same stream. It will me buch faster than doing IColumn::mutate, because mutate copies the whole column from the block if it's shared, it may be up to max_block_size rows instead of currently deserialized index_granularity rows (for compact parts, for wide we can read more at once, depending on which ranges we read).

With this approach, we can complitely remove usage of assumeMutable from the deserializations code. It will lead to some overhead of copying the data in some range, but maybe it's acceptable, depending on the overhead. Current approach with IColumn::mutate I think is not acceptable (it mae lead to 3-4x slowdown).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants