Repository navigation
Fix flaky 02477_single_value_data_string_regression and 02481_i43247_ubsan_in_minmaxany - #110632
Conversation
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]>
|
Workflow [PR], commit [2762660] Summary: ✅ AI ReviewSummaryThis PR is now a test-only CI fix: it broadens the malformed-state assertions in Final VerdictStatus: ✅ Approve |
…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.
|
Addressed the AI review's blocking finding in fac942c. The growth loop now only touches the 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 Verified against |
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]>
|
Note: #110630 fixes the same issue ( 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]>
…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]>
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]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code |
|
Done the other way, as suggested: the tests now accept 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 Verified with a binary that does not contain the reverted change (i.e. current 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 |
|
@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 |
|
Two independent failures in that run, not one. 1. The shard death: parallel-replicas unknown-stream, fix in progress The Aborting query, from the 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. This one has no fix in progress, and it is a real correctness bug, not a flake.
That makes The run confirms the split. Coordinator trace for the failing query:
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 Fixing this properly means changing the state format, and the existing Neither failure is related to your diff. |
|
Following up on the #112052 fixes exactly this root cause. I had independently arrived at the same mechanism and the same design (version the state, append Two measurements from my own investigation that may be worth having, both taken on unmodified master:
|
|
Update on the The write side is as described: 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: So on its own it fixes the stored column and the pre-54452 wire while turning a currently working distributed/ #112052 removes the precondition: it switches the 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. |
`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.
|
Closing the loop on the Re-measured on master |
Backport #110632 to 26.7: Fix flaky 02477_single_value_data_string_regression and 02481_i43247_ubsan_in_minmaxany
Related: #110630
Changelog category (leave one):
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_regression02481_i43247_ubsan_in_minmaxanyBoth 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::readallocates 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 expectedCANNOT_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 withMEMORY_LIMIT_EXCEEDED(241), so the tests failed.The behaviour is easy to see with any binary:
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::readto 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_refilltest 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 forSingleValueDataString::readdo 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
masterbehaviour):02477,02481and04550all pass both without a memory limit (theCANNOT_READ_ALL_DATAbranch) and with--max_memory_usage=500Mi(theMEMORY_LIMIT_EXCEEDEDbranch).Version info
26.8.1.293-master(included in26.8and later)26.7.35.14