Repository navigation
Reject aggregate function parameterisations whose state serializes to zero bytes - #119728
alexey-milovidov merged 7 commits into
Conversation
…bytes An aggregate function state can legitimately serialize to zero bytes. The -Resample combinator holds no nested states when its range is empty, through both arithmetic paths (end < begin, and end == begin), so its serialize() writes nothing and adds no framing of its own; covarSampMatrix and its siblings do the same when called with no arguments. ColumnAggregateFunction::serializeValueIntoArena then returns a valid arena pointer with size 0. Three sites asserted that this cannot happen, and aborted every build defining DEBUG_OR_SANITIZER_BUILD when it did: getKeyHolder<false> in KeyHolderHelpers.h, reached by the -Distinct combinator and by groupUniqArray, and both loops of AggregateFunctionGroupArrayIntersect, which open-code the same helper. The asserted invariant is false, not merely unreachable. An empty std::string_view key is the hash table's zero key, since ZeroTraits::check is x.empty(), so emplaceIfZero routes it to the dedicated zero-value slot, whose cell is default-constructed: no arena pointer is stored and nothing can dangle. Every other consumer of the same value already accepts it, including HashMethodSerialized for GROUP BY, getKeyHolder<true>, topK and groupArray. Deduplication stays correct because the function and its parameters are fixed within one column, so a zero-byte serialization carries no information and any two states producing one are equal. The line asserted serialized.data() != nullptr from 5abbaee until 45538fc tightened it during the StringRef to string_view migration. Restoring that older form would be dead weight: Arena::allocContinue asserts a non-zero request and WriteBufferFromArena::nextImpl clamps to at least one byte, so the data pointer is always a real arena address. I did not make the serialization non-empty instead. -Distinct, groupUniqArray and groupArrayIntersect write the raw key bytes into their own serialized state, so emitting a marker byte would change a persisted state format: a state written by a patched server would fail to read on an unpatched one. It would also fix one producer rather than the whole class.
groupArrayIntersect keeps two loops in add(): the first row an aggregate state receives goes through set.emplace, every later row through set.find. Reaching the second loop therefore needs one state to receive at least two rows, and the test's outer aggregation has no GROUP BY, so its ten rows are handed to AggregatingTransforms by thread. On a build that counts empty-key hits per loop, the split without a pin varies with the execution settings, from one state taking all ten rows to eight states taking one row each; with max_threads = 1 it is one first-loop hit and nine second-loop hits in every draw. The test exists to show that an empty serialized key is accepted in both loops, so that coverage should not depend on a setting the test runner randomizes. The control statement is pinned to match. Neither pin changes a result: all seven values are unchanged and the reference file is untouched. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewTwo rounds of internal review of this branch before publication, recorded for traceability. Nothing here Round 1, fixed.
💡 The invariant comment at Round 2, one disagreement recorded with its evidence.
💡 The description briefly cited |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260913-023800 |
|
Workflow [PR], commit [3818220] Summary: ✅
AI ReviewSummaryThis PR moves the fix to the producers of zero-byte aggregate states: empty-range Final Verdict✅ No new findings on the current head. LLVM Coverage ReportMeasured on commit 3818220.
Changed lines: Changed C/C++ lines covered: 20/23 (86.96%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 10 s compile time in total, 8 of them have a recent master baseline. |
This is still true. We need a non-empty serialization state to be able to deserialize element by element. Fix the violations instead. |
|
Understood, the assertion stays and I will fix the producers instead. Two producers reach
I will write a one-byte placeholder in If you would rather reject an empty I will also check the remaining aggregate functions for the same shape, keep the test, and push the replacement here. |
… zero bytes
A non-empty serialization is required to deserialize a column of aggregate
function states element by element, so chassert(!serialized.empty()) in
getKeyHolder<false> states a real invariant. This keeps all three of its sites
(KeyHolderHelpers.h, and both loops of AggregateFunctionGroupArrayIntersect,
which open-code the same helper) byte-identical to master, and fixes the two
producers that violated it instead.
Two parameterisations held nothing, so their states serialized to zero bytes and
aborted every build defining DEBUG_OR_SANITIZER_BUILD as soon as such a state
reached the -Distinct combinator, groupUniqArray or groupArrayIntersect:
SELECT length(countResampleMergeDistinct(10, 5, 1)(s))
FROM (SELECT countResampleState(10, 5, 1)(number, number) AS s
FROM numbers(10) GROUP BY number);
SELECT length(groupUniqArray(s))
FROM (SELECT covarSampMatrixState() AS s FROM numbers(3));
-Resample serializes its nested states in a bare for (i < total) loop with no
framing of its own, and total is 0 on both arithmetic paths of its constructor:
end < begin sets it directly, and end == begin computes (sum - 1) / step with
sum == step, which is 0 for every step >= 1. So countResample(10, 5, 1),
countResample(5, 5, 1) and sumResample(65535, 20, 1) all produce an empty state.
AggregateFunctionVarianceMatrixData::serialize writes one moment per pair of
arguments with no count field, and createAggregateFunctionVarianceMatrix
validated argument types but never arity, so covarSampMatrix(), covarPopMatrix()
and corrMatrix() were accepted with zero arguments although their registered
syntax is covarSampMatrix(x1[, x2, ...]).
Both are now rejected where the function is created. That is the same kind of
decision the -Resample constructor already makes twice, throwing
ARGUMENT_OUT_OF_BOUND for step == 0 and for a range with too many elements, with
the same consequence that a column type naming such a parameterisation fails to
load. Nothing usable is lost: because
SerializationAggregateFunction::deserializeBinaryBulk ends its loop on
istr.eof(), a persisted column of zero-byte states carries no bytes and reads
back as zero rows, which is CANNOT_READ_ALL_DATA on a MergeTree Compact part and
on Native, and a silently all-default column on a Wide part.
No serialized format changes, and that is deliberate.
docs/resources/develop-contribute/introduction/architecture.mdx:151 requires
backward compatibility for any change to an aggregate function's serialized
format, because AggregatingMergeTree persists these states. A one-byte
placeholder cannot supply it: a legacy state of one of these types wrapped by a
combinator that writes bytes of its own stops being readable, and an old peer
reading a new column consumes nothing while deserializeBinaryBulk still builds
limit rows, leaving the marker bytes to be read as the next column's name.
Gating the placeholder behind a state version does not help either, because a
version 0 state is still zero bytes and a legacy column is pinned at version 0.
This is why the commit reverses the reasoning of 1f26fe8 on this branch
and ships the alternative offered in
ClickHouse#119728 (comment)
rather than the placeholder promised in that same comment.
Three existing tests pinned the rejected behaviour and are updated, each keeping
its purpose:
02931_ubsan_error_arena_aligned_alloc asserted that a degenerate range must not
produce "applying non-zero offset 7 to null pointer". A rejected range cannot
reach the arena at all, so the statement keeps its subject and gains a
serverError annotation.
02427_msan_group_array_resample had one statement holding both a degenerate and
a non-degenerate Resample. Annotating it would have lost the MSan coverage of
the non-degenerate -State half, so it is split: the original statement keeps
that half with its reference line unchanged, and the degenerate aggregate moves
to a statement of its own.
03594_funcs_on_empty_arguments asserted that functions do not fall over on empty
arguments. A clean exception is not falling over, so the three matrix statements
gain serverError annotations and their three output lines leave the reference.
05210_empty_serialized_aggregate_state_key becomes the rejection test, with both
spellings of an empty range, the state-type spelling, the zero-argument matrix
case, and two controls: countResample(1, 5, 1), and countResample(4, 5, 1) as
the boundary that a total <= 1 predicate would break.
Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review of the redesigned change by an independent model (engine: codex; 0 findings on
Severity: ❌ blocker / Two checks that produced no finding, recorded because they are the ones worth doubting. Completeness: Session id: cron:clickhouse-review-slot-9:20260913-215900 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260913-212200 |
|
Pushed as 880ef88. I took the second option from my previous comment and rejected the two parameterisations at creation, rather than the placeholder byte I offered first. The placeholder would have changed the serialized format of two aggregate functions, and The audit I promised is done: of the 96 The category is now |
05211_backup_log_zero_byte_data_file built its zero-byte column from countResample(10, 5, 1), the parameterisation this branch rejects, so its first CREATE TABLE now fails with ARGUMENT_OUT_OF_BOUND and Fast test broke on the merge with master. An array column whose every value is empty leaves its element stream empty too: 100 rows put 0 bytes in s.bin next to 44 in s.size0.bin, on Log and on TinyLog. That is the same zero-size backup entry the restore path has to recreate, and it needs no aggregate function at all. Three arms went with the construction they required. They exercised StorageLog::backupData's emptiness predicate, which looks at the first data file, and an array column's first stream is its sizes stream, which always holds bytes. After this branch no supported input leaves that first file empty while the table holds data: a Nothing-typed column cannot be stored (StorageFactory.cpp checkAllTypesAreAllowedInTable) and Log implements no ADD COLUMN, so an aggregate state was the only single-stream column that could serialize to nothing. What is left covers BackupImpl::copyFileToDisk, measured both ways: the three restore arms lose their read line to FILE_DOESNT_EXIST on a binary without that fix, and the whole test passes 50/50 with randomization on one that has it.
|
Fast test caught a collision on this branch that I owe you the measurement for. The fixture now uses an array column whose values are all empty. That leaves the element stream at 0 bytes next to 44 bytes of array sizes, on Log and on TinyLog, which is the zero-size backup entry the test is about, and it needs no aggregate state at all. Worth flagging rather than leaving in the diff: three of that test's arms needed a whole column to occupy zero bytes, and they are gone with the construction they required. An array column's first stream is its sizes stream, a |
|
@groeneai @alexey-milovidov — title/description suggestions: Description (currently
Ignore if intentional. |
Pulls in the fix for the `countResample` zero-byte aggregate state logical error (ClickHouse#120549, fixed by ClickHouse#119728) that made `Stress test (arm_tsan)` red on https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118536&sha=90ee6c8f2dbc27508fd4344bdeb81501983bdb30&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 for ClickHouse#118536. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Related: #119727
Related: #119700
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
An aggregate function state that serializes to zero bytes cannot be read back, so the two parameterisations that produced one are now rejected: a
-Resamplecombinator over an empty range (begin >= end, such ascountResample(10, 5, 1)) throwsARGUMENT_OUT_OF_BOUND, andcovarSampMatrix,covarPopMatrixandcorrMatrixwith no arguments throwNUMBER_OF_ARGUMENTS_DOESNT_MATCH. Both returned an empty array before. No serialized format changes, but a table with such a column no longer loads. Before upgrading, drop the column where the engine supportsDROP COLUMN, and the whole table where it does not (Log,TinyLog,StripeLog,Set,Join,File).Description
countResample(10, 5, 1)andcovarSampMatrix()build states that serialize to zero bytes:-Resampleserializes its nested states with no framing and holds none over an empty range, and the variance-matrix creator never checked arity.getKeyHolder<false>asserts such a state is impossible, so a-Distinct,groupUniqArrayorgroupArrayIntersectaggregation over such a column aborted every debug or sanitizer build (AST fuzzer on #119700, both legs). Persisted, it is also unreadable: #119727.The assertion is right, so both producers are rejected where the function is created.
-Resamplealready throwsARGUMENT_OUT_OF_BOUNDforstep == 0and for too many elements, so neither check is new in kind. Nothing usable is lost: such a column carries no bytes and reads back as zero rows (CANNOT_READ_ALL_DATAon Compact parts and Native, all-default on Wide). Hence the category.Not a marker byte:
architecture.mdx:151requires backward compatibility for any serialized-format change, and a version cannot supply it, since a version 0 state is still zero bytes. This ships the alternative offered in that comment.Audit, as promised there: of the 96
serializeoverrides insrc/AggregateFunctions/, only these two were unguarded;-Tupleover an empty tuple andcategoricalInformationValue()at arity 0 are the same shape and existing checks reject both.Four existing tests pinned the old behaviour and keep their purpose;
05211's zero-byte data file now comes from an all-empty array column.What changed in each of the four
02931_ubsan_error_arena_aligned_alloc: a degenerate range must not reach the arena, and now cannot reach it.02427_msan_group_array_resample: split, so its non-degenerate-Statehalf keeps its MSan coverage.03594_funcs_on_empty_arguments: a clean exception is not falling over on empty arguments.05211_backup_log_zero_byte_data_file: an array column whose values are all empty leaves its element stream empty, so the backup entry it is about needs no aggregate state; measured, 0 bytes ins.binnext to 44 ins.size0.binon Log and TinyLog. The three arms that needed a whole column to occupy zero bytes are gone with the construction they required: an array column's first stream is its sizes stream, aNothing-typed column cannot be stored, andLogimplements noADD COLUMN, so after this change nothing reachable from SQL leaves a Log family table's first data file empty while the table holds data, andStorageLog::backupData's emptiness predicate is no longer pinned by a test. What remains still fails on a binary without theBackupImpl::copyFileToDiskhalf of that fix, and passes 50/50 with randomization on one that has it.Workflow [PR]
Sync PR [sync-upstream/pr/119728]
Version info
26.10.1.137(included in26.10and later)