Skip to content

Fix flaky 02477_single_value_data_string_regression and 02481_i43247_ubsan_in_minmaxany - #110632

Merged
alexey-milovidov merged 14 commits into
masterfrom
fix-single-value-string-read-oom
Jul 28, 2026
Merged

alexey-milovidov merged 14 commits into
masterfrom
fix-single-value-string-read-oom

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

Related: #110630

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Not for changelog.

Documentation entry for user-facing changes

Not needed.


Two stateless tests were flaky in CI:

  • 02477_single_value_data_string_regression
  • 02481_i43247_ubsan_in_minmaxany

Both read AggregateFunction(min/max, String) states whose 4-byte size prefix declares up to 2 GiB while the state actually carries ~100 KB or less. SingleValueDataString::read allocates the declared size in the arena before reading a single byte of the value, so it discovers that the data is short only after that allocation. Without a memory limit in the way, the query fails with the expected CANNOT_READ_ALL_DATA (33); under memory pressure — many stateless tests running in parallel, especially in sanitizer builds — the allocation is refused first and the query fails with MEMORY_LIMIT_EXCEEDED (241), so the tests failed.

The behaviour is easy to see with any binary:

$ clickhouse local --query "SELECT maxMerge(x) FROM (SELECT CAST(unhex('ffffff7f') || randomString(100500), 'AggregateFunction(max, String)') AS x)"
Code: 33. DB::Exception: Cannot read all data. Bytes read: 100500. Bytes expected: 2147483646 ... (CANNOT_READ_ALL_DATA)

$ clickhouse local --query "SELECT maxMerge(x) FROM (SELECT CAST(unhex('ffffff7f') || randomString(100500), 'AggregateFunction(max, String)') AS x) SETTINGS max_memory_usage = '500Mi'"
Code: 241. DB::Exception: Query memory limit exceeded: would use 2.00 GiB (attempt to allocate chunk of 2.00 GiB), maximum: 500.00 MiB ... (MEMORY_LIMIT_EXCEEDED)

Failed CI report: Stateless tests (amd_asan_ubsan, distributed plan, parallel) on master @ 81f8ef5172094f3a8abe5b01e3fe9fdc68307951.

Fix

Both error codes are correct: the property under test is that a corrupted state is rejected, not which of the two errors is reported. So the affected queries now accept either code (-- { serverError CANNOT_READ_ALL_DATA, MEMORY_LIMIT_EXCEEDED }), and the read path is left alone.

Earlier revisions of this pull request changed SingleValueDataString::read to grow the buffer as it reads instead of trusting the declared size, which made the error code deterministic. That was reverted: it staged the value in a separate buffer, so on the multi-refill path (a state larger than the read buffer) the staged copy and the arena buffer briefly coexisted and the tracked peak was about twice the payload — not worth paying to pin down an error code. The alternative of growing the arena allocation in place (Arena::allocContinue, the approach of #110630) permanently strands every superseded copy in the arena until the query ends. This pull request is now test-only; there is no change in behaviour for users.

The 04550_single_value_data_string_multi_refill test that came out of that work is kept: it reads back a valid 8 MB state that spans many 64 KiB compressed blocks, which the existing tests for SingleValueDataString::read do not exercise (they all read states that fit into a single buffer).

Verified locally with a binary that does not contain the reverted change (i.e. current master behaviour): 02477, 02481 and 04550 all pass both without a memory limit (the CANNOT_READ_ALL_DATA branch) and with --max_memory_usage=500Mi (the MEMORY_LIMIT_EXCEEDED branch).

Version info

  • Merged into: 26.8.1.293-master (included in 26.8 and later)
  • Backported to: 26.7.35.14

SingleValueDataString::read() reserved the entire size prefix (up to ~2 GiB)
before reading the value. A corrupted or truncated AggregateFunction(min/max,
String) state with a huge size prefix therefore forced a multi-gigabyte arena
allocation and could fail with MEMORY_LIMIT_EXCEEDED under memory pressure,
instead of the expected CANNOT_READ_ALL_DATA. This is what made the tests
02477_single_value_data_string_regression and 02481_i43247_ubsan_in_minmaxany
flaky (they assert CANNOT_READ_ALL_DATA for such inputs).

Grow the destination buffer gradually while reading instead, so a short buffer
fails with CANNOT_READ_ALL_DATA after allocating only as much memory as the data
really occupies. For valid data the final capacity and the amount read are
unchanged. Also add a regression assertion with a tight max_memory_usage so the
behavior is checked deterministically rather than relying on incidental memory
pressure from parallel test runs.

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

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2762660]

Summary: ✅


AI Review

Summary

This PR is now a test-only CI fix: it broadens the malformed-state assertions in 02477_single_value_data_string_regression and 02481_i43247_ubsan_in_minmaxany to accept either CANNOT_READ_ALL_DATA or MEMORY_LIMIT_EXCEEDED, and it keeps coverage for valid multi-refill deserialization with 04550_single_value_data_string_multi_refill after reverting the runtime change in SingleValueDataString::read. I reviewed the current diff, prior inline threads, linked discussion, and current green CI, and I did not find a remaining correctness or coverage issue worth blocking.

Final Verdict

Status: ✅ Approve

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

The AI review on this PR pointed out that growing the destination
directly in the Arena means every intermediate allocation made while
draining a value that spans multiple buffer refills stays alive until
the whole Arena is freed - a real (bounded ~2x) memory regression for
valid large states read in several chunks.

Address it: when the whole value is already sitting in the read
buffer (the common case), allocate once directly in the arena exactly
as before this PR - no change on that path. Otherwise, grow a plain
heap buffer while reading (ordinary reallocation frees the previous
buffer as it grows, so no leftover waste) and copy the fully-read and
validated value into the arena in a single final allocation.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review's blocking finding in fac942c.

The growth loop now only touches the Arena when the whole value is already sitting in the read buffer (the common case for AggregateFunction(min/max, String)/argMin/argMax states, since they are almost always much smaller than the read buffer) - in that case it's a single allocation directly into the arena, identical to the pre-fix code, with zero waste.

Only when the value spans more than what is currently buffered (a genuinely large state, or a short/corrupt one) does it grow a buffer while reading - but now on plain heap memory instead of the Arena. Ordinary heap reallocation frees the previous buffer as it grows, so no intermediate copies are kept alive. Once the whole value has been read and validated, it's copied into the Arena in one final allocation. This fully removes the permanent-waste concern the review raised, with no extra cost on the common path.

Verified against 02477_single_value_data_string_regression and 02481_i43247_ubsan_in_minmaxany (both match their .reference output) plus the maxMerge repro from the PR description under max_memory_usage = '500Mi'.

The AI review pointed out that the previous growth loop still resized
the scratch buffer geometrically (scratch.size() * 2, capped only by the
untrusted declared size) before the next bytes were proven to exist. A
truncated state whose actual data is large but short of the declared
size could therefore still trigger a near-declared-size speculative
allocation on the final failing iteration and return
MEMORY_LIMIT_EXCEEDED instead of CANNOT_READ_ALL_DATA.

Accumulate the value in chunks instead, each sized exactly to the bytes
already sitting in the (refilled) read buffer, and copy them into the
arena in a single allocation only after the whole value has been read.
Allocations are now bounded by the data that actually exists, never by
the declared size.

Verified: a state declaring 2^31-1 bytes with 900 MB of actual data
under a 2.5 GB memory limit now fails with CANNOT_READ_ALL_DATA (the
doubling would have needed ~3.6 GB transiently). Also add a test that a
valid 8 MB state spanning many 64 KiB compressed blocks (multiple read
buffer refills) round-trips unchanged through the new path.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Note: #110630 fixes the same issue (SingleValueDataString::read preallocating the untrusted declared size upfront, flipping CANNOT_READ_ALL_DATA to MEMORY_LIMIT_EXCEEDED for corrupted states under memory pressure) with a different approach (Arena::allocContinue there vs. exact-size chunk accumulation with a single final arena allocation here). Only one of the two should be merged.

Related: #110630

…style check

The style check forbids plain `std::vector` in `src/AggregateFunctions` because
its allocations are tracked only via non-throwing methods of `MemoryTracker`.
`VectorWithMemoryTracking` uses `AllocatorWithMemoryTracking`, which throws on
reaching the memory limit - exactly what we want when accumulating chunks of a
large aggregate state near the limit. Also drop the now-unneeded `<vector>`
include.

Style check report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110632&sha=f03b0c5d2bc2f11b085e257d0b32841394bbb6ad&name_0=PR&name_1=Style%20check

Co-Authored-By: Claude Fable 5 <[email protected]>
Address review feedback on the chunked read path of
`SingleValueDataString::read`: the staged chunks were plain `String`s.
Standard containers are tracked through the *non-throwing* new/delete
path (see `VectorWithMemoryTracking.h`), and with the default
`min_allocation_size_to_throw_on_memory_limit = 0` the global `operator
new` never enforces the limit (`allocThrow` compares against
`UInt64::max()`), so a multi-refill state could stage hundreds of MiB
past `max_memory_usage` and only fail with `CANNOT_READ_ALL_DATA` at
EOF. That weakened the memory-limit contract compared to the old
single-arena path (the arena uses `AllocatorWithMemoryTracking`, which
always enforces via `CurrentMemoryTracker::alloc`).

Stage the chunks in `StringWithMemoryTracking` (backed by
`AllocatorWithMemoryTracking`) so the accumulated payload is refused with
`MEMORY_LIMIT_EXCEEDED` as it grows, exactly like the old path, instead
of being merely counted.

Verified with the built binary: `02477`, `02481`, `04550` pass; a 10 MB
`AggregateFunction(max, String)` state read via many read-buffer refills
round-trips under a generous limit but is refused with
`MEMORY_LIMIT_EXCEEDED` (attempt to allocate a chunk) under an 8 MiB
limit, while a truncated state under a tight limit still fails with
`CANNOT_READ_ALL_DATA`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Jul 17, 2026
…String::read

The staging buffer was a plain `String`, whose heap allocations go through
the global `operator new`: they are counted against the query memory limit
but not refused when it is exceeded. A corrupted state with a large actual
payload could therefore stage arbitrarily many bytes past `max_memory_usage`
before failing with `CANNOT_READ_ALL_DATA` at EOF, weakening the memory-limit
contract compared to the old single-`Arena`-allocation path.

Use `StringWithMemoryTracking` (backed by `AllocatorWithMemoryTracking`,
which calls the enforcing `CurrentMemoryTracker::alloc`), so the limit is
enforced as the staging buffer grows — the same fix that was applied to the
sibling PR #110632.

Verified: `02477_single_value_data_string_regression` and
`02481_i43247_ubsan_in_minmaxany` pass; a 10 MB `argMax(String)` state
written in 64 KiB compressed blocks (~150 read-buffer refills) round-trips
byte-for-byte, and the same read under `max_memory_usage = '8Mi'` is now
refused with `MEMORY_LIMIT_EXCEEDED` during staging.

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov and others added 2 commits July 25, 2026 11:02
The AI review on the merge commit re-raised the transient double-buffer
finding at the final hand-off of `SingleValueDataString::read`: the
staged chunks and the freshly allocated arena buffer briefly coexist,
making the tracked peak about twice the payload on the multi-refill
path. Acknowledge this failure mode explicitly in the code, as the
review suggests: it is inherent to staging untrusted bytes before a
single arena commit - trusting the declared size upfront is the
original bug, and `Arena::allocContinue` strands superseded copies in
the arena until the query ends. The path is taken only when a value
spans more than one read-buffer refill; the common case is unchanged.

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

clickhouse-gh Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.30% -0.10%

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

Full report · Diff report

@alexey-milovidov alexey-milovidov changed the title Do not preallocate untrusted size when reading min/max String aggregate state Fix flaky 02477_single_value_data_string_regression and 02481_i43247_ubsan_in_minmaxany Jul 25, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Done the other way, as suggested: the tests now accept MEMORY_LIMIT_EXCEEDED as well as CANNOT_READ_ALL_DATA, and the change to SingleValueDataString::read is reverted (0c06a6d) — that file is byte-for-byte identical to master again, so this pull request is test-only.

The hint syntax already supports a list of codes, so it is a one-line change per query:

-- { serverError CANNOT_READ_ALL_DATA, MEMORY_LIMIT_EXCEEDED }

Applied to the five oversized-size-prefix queries in 02477_single_value_data_string_regression and to the 'Aggr'-prefixed state in 02481_i43247_ubsan_in_minmaxany (the only queries whose declared size, up to 2 GiB, can make the arena allocation fail before the short data is detected). Both outcomes are correct — the property under test is that a corrupted state is rejected — and each site says so in a comment.

Verified with a binary that does not contain the reverted change (i.e. current master behaviour): 02477, 02481 and 04550 pass both without a memory limit (all the corrupted states give CANNOT_READ_ALL_DATA) and under --max_memory_usage=500Mi (they all give MEMORY_LIMIT_EXCEEDED), so either branch of the hint is actually exercised.

What is given up: a corrupted state still triggers a transient allocation of the declared size, up to ~2 GiB, before failing. It is refused by the memory tracker rather than causing any real harm, so the robustness gain was not worth the extra copy on the read path.

I kept 04550_single_value_data_string_multi_refill from the reverted work — it reads back a valid 8 MB state spanning many 64 KiB compressed blocks, which the existing tests for this function do not cover (they all read states that fit into a single buffer). Happy to drop it if you'd rather keep this strictly to the hint change.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110632&sha=0c06a6dccbcd21f080d9bae6660779894cf394d4&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The shard died with Logical error '!part.empty()', which took 01913_quantile_deterministic and the rest of the shard down with it. It is unrelated to this pull request (the diff is test-only: two serverError hints and one new stateless test). It is a master-wide flake — over the last 10 days play.clickhouse.com shows Logical error '!part.empty()' failing 150+ times across 100+ different pull requests, and I could not find an open issue tracking it.

@groeneai

Copy link
Copy Markdown
Collaborator

Two independent failures in that run, not one. 01913_quantile_deterministic is not collateral of the shard death: it failed at 07:17:12 (runner clock) while the server aborted at 07:23:41, six and a half minutes later, and the job kept running tests until 07:23:41. Its diff is a wrong value, not a dead connection.

1. The shard death: parallel-replicas unknown-stream, fix in progress

The !part.empty() label is a log-scan co-match, not the abort. grep -a "part.empty()" over the whole clickhouse-server.err.log returns exactly one line, and it is the SQL comment of 04367_lambda_arg_backquoted_dot_no_logical_error (which passed, at 07:16:29). The only <Fatal> in the log is:

Logical error: 'Got read request from replica 2 for unknown stream test_c1g0rfxf.`.inner_id.5e5db72f-...`'
src/Storages/MergeTree/ParallelReplicasReadingCoordinator.cpp:1295: ParallelReplicasReadingCoordinator::handleRequest
src/QueryPipeline/RemoteQueryExecutor.cpp:869: processMergeTreeReadTaskRequest

Aborting query, from the BaseDaemon: ... Received signal line: SELECT count() FROM mv WHERE id = 999999999 (test 04493_create_or_replace_materialized_view_populate_keeps_subscription_concurrent). The initiator log shows why: optimizeUseAggregateProjections: Exact count optimization is applied fires on the initiator, so its ReadFromMergeTree is replaced by a prepared source and never announces its read set; the coordinator registers no stream, then Ignoring announcement from non-snapshot replica 2 for unknown stream and the follower's read request hits the null coordinator.

Tracked in #110518. My fix is open: #111689 (announce the empty read set from the projection optimizer when the short-circuit leaves no parent parts). Not merged, so branches still hit it.

2. 01913_quantile_deterministic: quantileDeterministic state serialization drops skip_degree

This one has no fix in progress, and it is a real correctness bug, not a flake.

ReservoirSamplerDeterministic thins its reservoir once it exceeds max_sample_size (8192): insertImpl raises skip_degree and thinOut() keeps only samples with (hash & skip_mask) == 0. But write()/read() (src/AggregateFunctions/ReservoirSamplerDeterministic.h) serialize only samples and total_values. skip_degree and skip_mask are never written, so a deserialized state comes back claiming skip_degree == 0.

That makes merge() wrong in one direction only. Locally, both states are compared and the lower one is raised to the higher (if (skip_degree < b.skip_degree) setSkipDegree(b.skip_degree)). After a round trip the thinned state looks unthinned, that raise never happens, and samples from the unthinned side that should have been dropped are kept, biasing the quantile upward. Consistent with the failure being a single wrong value in a 20x loop: it only shows when the read is actually split across replicas and one side crosses 8192.

The run confirms the split. Coordinator trace for the failing query:

Going to respond to replica 0 with 1 parts: [all_122_122_0[(0, 1)]]
Going to respond to replica 1 with 3 parts: [all_1_116_23[(0, 116)], all_117_121_1[(0, 5)], all_123_123_0[(0, 1)]]

query_log for that query: initiator read_rows = 1000000, follower 599bc431 read_rows = 991808, the other follower 0. So replica 0 read one 8192-row granule, replica 1 read the remaining 991808 (121 marks). No rows lost, 8192 + 991808 = 1000000. All 19 other loop iterations ran entirely on the initiator (both followers read_rows = 0) and returned 492708, which is why only line 1 differs.

Reproduced exactly on current master, no cluster needed, forcing the serialization round trip that the remote read performs:

WITH src AS (SELECT number AS oid FROM numbers(1000000)),
     tagged AS (SELECT oid, (oid >= 991232 AND oid < 999424) AS on_initiator FROM src)
SELECT medianDeterministicMerge(s) FROM (SELECT medianDeterministicState(oid,oid) AS s FROM tagged GROUP BY on_initiator);
-- 492708  (in-memory merge, correct)

WITH src AS (SELECT number AS oid FROM numbers(1000000)),
     tagged AS (SELECT oid, (oid >= 991232 AND oid < 999424) AS on_initiator FROM src)
SELECT medianDeterministicMerge(CAST(unhex(h) AS AggregateFunction(medianDeterministic, UInt64, UInt64)))
FROM (SELECT hex(medianDeterministicState(oid,oid)) AS h FROM tagged GROUP BY on_initiator);
-- 503971  (after round trip)

503971 is the exact value the test printed. With both partial states under 8192 rows the round trip is lossless (5014 both ways), which isolates it to skip_degree.

Fixing this properly means changing the state format, and the existing write() already carries a comment that the format is wrong and needs versioned aggregate state, so I want to avoid guessing at the compatibility story. I will open a separate PR for it. Report URL for the record: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110632&sha=0c06a6dccbcd21f080d9bae6660779894cf394d4&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29

Neither failure is related to your diff.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 28, 2026
Merged via the queue into master with commit faf4b94 Jul 28, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-single-value-string-read-oom branch July 28, 2026 18:04
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 28, 2026
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

Following up on the 01913_quantile_deterministic investigation above: the fix is already in progress, and it is yours, so I am linking it rather than opening a competing PR.

#112052 fixes exactly this root cause. ReservoirSamplerDeterministic::write/read never serialized skip_degree, so a deserialized thinned state reported skip_degree == 0; because merge only raises in one direction, samples that the higher skip mask should have dropped were retained and the quantile came out biased. That is the -492708 / +503971 diff, and it needs no crash to happen.

I had independently arrived at the same mechanism and the same design (version the state, append skip_degree in version 1 keeping the version-0 prefix byte-identical, gate it on a new revision with the protocol version bumped in the same commit). Since #112052 already implements that, plus the setVersionToAggregateFunctions and NativeWriter fixes I had not identified, there is nothing useful for me to add in a separate PR.

Two measurements from my own investigation that may be worth having, both taken on unmodified master:

  1. The precondition is narrower than "a partial state exceeded 8192 rows". The merged states must have different skip_degree; when they are equal, losing the field leaves them still equal and the result does not move. Two identical 8193-row shards give 3997.5 both in memory and through a round trip, while 100 rows merged with 100000 gives 50345.5 in memory versus 49549 through a round trip. That is why 01533_quantile_deterministic_assert keeps its recorded 3997.5 under your patch even though each of its shards is thinned.

  2. There is one carrier Fix non-deterministic quantileDeterministic under parallel replicas and distributed queries #112052 does not cover: the -ForEach combinator discards the state version on the write side. AggregateFunctionForEach::serialize takes std::optional<size_t> /* version */ and calls nested_func->serialize(nested_state, buf) with no version, while deserialize forwards it and all three version accessors are delegated to the nested function. With an already versioned nested function this is observable today without quantileDeterministic at all: a version-0 and a version-1 declared sumMapForEach state serialize to identical bytes, both carrying the version-1 payload, and a version-0-pinned column reads back [([1],[3])] instead of [([1,2],[3,4])] with no error, while the same shape over bare sumMap reads back correctly. Once quantileDeterministic becomes versioned, quantileDeterministicForEach joins that set. I am tracking it separately and will send a PR for it, since it is a combinator concern with its own compatibility question rather than part of this one.

@groeneai

Copy link
Copy Markdown
Collaborator

Update on the -ForEach carrier I said I would send a separate PR for: the one-line fix is right, but it is not safe until #112052 lands, so I am holding it rather than opening it now.

The write side is as described: AggregateFunctionForEach::serialize drops the version. What I had not measured is the modern wire, and it changes the conclusion. On unmodified master a version-0-declared sumMapForEach state read back in flight over a normal client/server connection is correct ([([1,2],[3,4])]), because two defects cancel: my combinator writes the v1 payload, and the receiver cannot see the pinned 0 (getNameImpl does not print version 0) so it derives 1 from the negotiated revision. v1 payload, v1 parse.

Forwarding the version alone breaks that cancellation. The writer would emit a correct v0 payload under a versionless type name, and the receiver would still read it as v1:

v0 bytes, v0 reader -> [([1,2],[3,4])]
v0 bytes, v1 reader -> Code: 33 CANNOT_READ_ALL_DATA. Bytes read: 3. Bytes expected: 8

So on its own it fixes the stored column and the pre-54452 wire while turning a currently working distributed/remote() path into a hard error. The bare sumMap control is correct on every path, which is what isolates it to the combinator.

#112052 removes the precondition: it switches the NativeWriter call to if_empty = client_revision == 0, so a modern peer derives the version instead of preserving the pin, and it adds hasExplicitVersion() which does not exist on master yet. Your comment in that diff describes this exact mechanism for the pre-versioning pinned-to-0 case. It does not touch -ForEach itself, so the two changes are complementary, but only in that order.

I will send the combinator fix once #112052 is merged, revalidating both wire directions on that base. Nothing to do on your side; flagging it because I said I would send it and the ordering turned out to matter.

middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Sep 4, 2026
`deserialize` read a size out of an untrusted aggregate state and then reserved,
resized or allocated that much before reading the payload meant to back it.
`readVarUInt` has no maximum, and the bounds that exist are element counts, which
cannot bound an allocation: a count cap N still admits N * sizeof(element) bytes.
ClickHouse#108465 capped the counts at four of these sites and left exactly that residual.

Six bytes of state (`unhex('808080800400')`, which is exactly
MAX_STATISTICS_STATE_SIZE and so passes its strict `>`) requested 8.00 GiB through
StatisticalSample::read. Tracked peak for that state is now 31.70 KiB, and for a
legitimate state it is byte-identical before and after.

The sites read payload-first instead, choosing a mechanism per destination: clamp
a reserve that is only an optimization to what the buffer already holds; grow a
PODArray in place, the way addX/addY already fill those same arrays; grow a String
destination directly; or, for an Arena, allocate once after staging the payload
outside it, since an Arena cannot reuse a superseded block. Every count * width
product is checked with common::mulOverflow using serialized widths rather than
sizeof(Element), which differ for timeSeriesGroupArray because Element is padded.
A -Map state that repeats a key is now rejected, since serialize() walks a map and
cannot emit one, while each repetition used to allocate a nested state that
emplace then dropped.

No cap, error code, constant or allocation policy moves, and the fully-buffered
path is unchanged, so there is no format change, no setting and no compatibility
shim. groupBitmap keeps a plain String rather than a tracking container precisely
to preserve its counted-but-not-refused allocation policy, because 8d044e8
raised its bound to 100 GiB for real user states. This is deliberately not a
universal claim: SingleValueDataString::read still allocates from its declared
size, by 6594a77, and is untouched here.

The mechanism follows the arc of PR ClickHouse#110632, whose last commit reverted it for
test determinism rather than on a fault in the design; here it is the only remedy
that closes the finding without rejecting states the current writer can produce.

Comments left over-budget by ClickHouse#108465 in StatCommon.h, GroupArrayIntersect.cpp and
SequenceMatch.cpp are trimmed to the invariant they state.
@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Closing the loop on the -ForEach fix I said I was holding: #115393 forwards version in AggregateFunctionForEach::serialize, so I am not sending a separate PR.

Re-measured on master b5446bf (official build): a sumMapForEach column declared with version 0 now reads back [([1,2],[3,4])] (it was [([1],[3])] on 468fbe0). remote() (in-flight state and stored column) and a Native file round trip also read it back correctly, so the CANNOT_READ_ALL_DATA case I described above does not occur.

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 20, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 20, 2026
Backport #110632 to 26.7: Fix flaky 02477_single_value_data_string_regression and 02481_i43247_ubsan_in_minmaxany
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-ci 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.7-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants