Skip to content

Reject aggregate function parameterisations whose state serializes to zero bytes - #119728

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:allow-empty-serialized-state-hash-key
Sep 19, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:allow-empty-serialized-state-hash-key

Conversation

@groeneai

@groeneai groeneai commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119727
Related: #119700

Changelog category (leave one):

  • Backward Incompatible Change

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 -Resample combinator over an empty range (begin >= end, such as countResample(10, 5, 1)) throws ARGUMENT_OUT_OF_BOUND, and covarSampMatrix, covarPopMatrix and corrMatrix with no arguments throw NUMBER_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 supports DROP COLUMN, and the whole table where it does not (Log, TinyLog, StripeLog, Set, Join, File).

Description

countResample(10, 5, 1) and covarSampMatrix() build states that serialize to zero bytes: -Resample serializes 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, groupUniqArray or groupArrayIntersect aggregation 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. -Resample already throws ARGUMENT_OUT_OF_BOUND for step == 0 and 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_DATA on Compact parts and Native, all-default on Wide). Hence the category.

Not a marker byte: architecture.mdx:151 requires 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 serialize overrides in src/AggregateFunctions/, only these two were unguarded; -Tuple over an empty tuple and categoricalInformationValue() 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 -State half 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 in s.bin next to 44 in s.size0.bin on 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, a Nothing-typed column cannot be stored, and Log implements no ADD COLUMN, so after this change nothing reachable from SQL leaves a Log family table's first data file empty while the table holds data, and StorageLog::backupData's emptiness predicate is no longer pinned by a test. What remains still fails on a binary without the BackupImpl::copyFileToDisk half of that fix, and passes 50/50 with randomization on one that has it.

Workflow [PR]
Sync PR [sync-upstream/pr/119728]

Version info

  • Merged into: 26.10.1.137 (included in 26.10 and later)

groeneai and others added 2 commits September 13, 2026 01:49
…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two rounds of internal review of this branch before publication, recorded for traceability. Nothing here
asks for action from anyone reading it.

Round 1, fixed.

⚠️ groupArrayIntersect's second loop was covered only by luck. add() reaches its subsequent-rows
loop (it = set.find(serialized)) only when a single aggregate state receives at least two rows, and the
test's outer aggregation has no GROUP BY, so its rows are split across threads. Instrumented at
max_threads=32 the statement recorded 10 first-loop hits and 0 second-loop hits while still returning the
expected value, so an assertion re-introduced on that line could have passed a randomized run. Fixed by
pinning max_threads = 1 on the two groupArrayIntersect statements. Honest limit on that measurement: the
unpinned statement could not be made to miss the loop again, in 106 further configurations. What a counting
build did confirm, over 60 randomized draws, is the mechanism behind the risk: unpinned, the ten rows fan out
into 1, 4 or 8 aggregate states depending on the execution settings; pinned, it is one first-loop hit and
nine second-loop hits in every draw. So the pin removes the variance rather than repairing a hole seen twice.

💡 The invariant comment at KeyHolderHelpers.h was challenged for citing hash-table internals and kept
after verification: it holds for both consumers of getKeyHolder<false>, and the zero-storage-less
ClearableHashSet path is safe at size 0 as well, since WriteBufferFromArena::complete() leaves the arena
head at the key's own address.

Round 2, one disagreement recorded with its evidence.

⚠️ Claim: the -Distinct statement would still pass if the empty key were silently discarded, so it does
not prove key acceptance.
The premise is correct. That statement expects 0 because an empty -Resample
range has no buckets: insertResultIntoImpl loops 0..total, so with total == 0 the array is empty
whatever the input, and the value cannot distinguish a stored key from a dropped one. The conclusion does not
follow. The line deleted at that site is in the shared getKeyHolder helper, and two other shipped statements
pin that same line with a value that collapses to 0 if the key is dropped: groupUniqArray over the same
states returns 1, and a zero-argument covarSampMatrix state returns 1. On a build where only that one
assertion is restored, all three statements abort, so all three demonstrably execute the line. The two
open-coded lines are pinned the same way by the groupArrayIntersect statement, 1 against its control's
0. So the acceptance contract is pinned by the test; what the -Distinct statement uniquely adds is the
no-abort oracle on the exact frame the fuzzer hit. Noted and not blocking: a future change to the -Distinct
combinator's own insertion gating, rather than to the shared helper, would not be caught by that statement
alone.

💡 The description briefly cited bitEquals(x, T{}) for the zero-key check after I over-corrected it.
std::string_view has its own ZeroTraits::check overload returning x.empty(), which is what the
description says now. Both spellings agree that a zero-size view is the zero key, so nothing in the reasoning
changed.

@clickhouse-gh clickhouse-gh Bot closed this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no randomization needed. SELECT length(countResampleMergeDistinct(10, 5, 1)(s)) FROM (SELECT countResampleState(10, 5, 1)(number, number) AS s FROM numbers(10) GROUP BY number); aborts a debug binary with Logical error: '!serialized.empty()' on every run. Also reproduced against a real server, where the stack matches the fuzzer's frame for frame: KeyHolderHelpers.h:28 under AggregateFunctionDistinct.h:91 / :261, Aggregator, AggregatingTransform.
b Root cause explained? Yes. -Resample sets total = 0 for an empty range, through both arithmetic paths (end < begin, and end == begin), so serialize() is a zero-iteration loop that adds no framing and writes 0 bytes; ColumnAggregateFunction::serializeValueIntoArena returns a valid arena pointer with size 0; three sites asserted that value is impossible. The assertion is the defect: an empty std::string_view key is the hash table's zero key (ZeroTraits::check is x.empty()), so emplaceIfZero puts it in the dedicated zero-value slot, whose cell is default-constructed, so no arena pointer is retained.
c Fix matches root cause? Yes, and no band-aid. The three false assertions are deleted at their own sites. Restoring the pre-2025 chassert(serialized.data() != nullptr) was rejected as provably unfirable (Arena::allocContinue asserts a non-zero request; WriteBufferFromArena::nextImpl clamps to at least one byte). Emitting a marker byte was rejected because -Distinct, groupUniqArray and groupArrayIntersect persist the raw key bytes in their own state, so it would change a state format between versions, and it fixes one producer rather than the class.
d Test intent preserved / new tests added? New test 05210_empty_serialized_aggregate_state_key, 7 statements: one per fixed site with a zero-byte state, three non-empty-range controls, and one non-Resample trigger. The .reference was derived from the semantics first and then matched the observed output exactly. Statements 3 and 6 return different values (1 and 0), so neither line is satisfied by a stuck implementation. The two groupArrayIntersect statements pin max_threads = 1 so that one aggregate state receives all ten rows and both of that function's loops are reached by construction instead of depending on how the runner happens to randomize the thread count. No existing test was weakened; the fuzzer's seeding test 05055 is untouched.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (base 13263a4d..., fix 60ac9aaa...). Statements 1, 2, 3 and 7 abort with rc=134 on base and return 0, 1, 1, 1 on fix; controls return [1,1,1,1], 5, 0 on both. Through the real runner the test killed a base server (ClickHouse server died during test, server exit 134) and passes on fix, with both server identities asserted from SELECT lower(buildId()) before the verdict. 100/100 randomized runs green, with 78 to 106 settings per query, so randomization was live.
f Fix is general across code paths? Yes. A full-tree grep found the assertion at exactly three sites, not the one in the report: the shared helper plus both loops of groupArrayIntersect, which open-code it. All three are fixed, and each deleted line has its own mutation arm, rebuilt one assertion at a time, proving a shipped statement covers it: the shared helper at KeyHolderHelpers.h:28, the set.emplace loop, and the set.find loop. Sibling producers that never asserted (getKeyHolder<true>, HashMethodSerialized, topK, multi-argument -Distinct) were measured tolerant on base, so they need no change.
g Fix generalizes across inputs? Yes. The trigger is a property of the state, not of a wrapper: Nullable, LowCardinality, Array, Map, Tuple, Variant and Dynamic each write their own prefix, so a wrapped state is never a 0-byte key. Both -Resample arithmetic paths are covered (end < begin shipped, end == begin measured), and statement 7 covers a second, unrelated producer family: covarSampMatrix called with no arguments, which also aborts on base and passes on fix.
h Backward compatible? Yes, fully. No setting, no default, no state format, no wire protocol and no serialized layout changes, so no SettingsChangesHistory.cpp entry applies. Deleting a chassert cannot change behaviour in any build without DEBUG_OR_SANITIZER_BUILD, where chassert_1 already expands to (void)sizeof(!(x)). Avoiding a state-format change is precisely why the marker-byte alternative was rejected.
i Invariants and contracts preserved? Yes. The deleted lines asserted a precondition that the hash table never required: emplaceIfZero handles the empty key by design, setHasZero default-constructs the zero cell so no caller pointer is stored, and emplace neither persists nor discards a zero key, which leaks nothing because a 0-size complete() has already rolled the arena back. deserializeAndInsert round-trips an empty state (ReadBufferFromString("") is immediately at eof). keyHolderDiscardKey's own chassert was exercised with a duplicate non-empty key and did not fire.

Session id: cron:clickhouse-impl-slot-4:20260913-023800

@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3818220]

Summary: ✅


AI Review

Summary

This PR moves the fix to the producers of zero-byte aggregate states: empty-range ...Resample aggregates and zero-argument covarPopMatrix / covarSampMatrix / corrMatrix are now rejected at creation time, the user-facing docs were updated to match, and the affected stateless tests were rewritten around the new contract. After reviewing the current diff together with the prior PR discussion and existing review threads, I did not find any remaining issue that warrants a new inline comment.

Final Verdict

✅ No new findings on the current head.

LLVM Coverage Report

Measured on commit 3818220.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.40% -0.10%

Changed lines: Changed C/C++ lines covered: 20/23 (86.96%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 381822043 with master 0d04f2bc2 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

8 translation units recompiled, 10 s compile time in total, 8 of them have a recent master baseline.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member

assuming an aggregate function state cannot serialize to zero bytes

This is still true. We need a non-empty serialization state to be able to deserialize element by element. Fix the violations instead.

@alexey-milovidov alexey-milovidov self-assigned this Sep 13, 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.

.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, the assertion stays and I will fix the producers instead.

Two producers reach KeyHolderHelpers.h:28, both measured on a debug build:

  1. The -Resample combinator: serialize loops over total nested states, and total is 0 for an empty range, which is end < begin and also end == begin. countResampleMergeDistinct(10, 5, 1) and (5, 5, 1) over countResampleState columns both abort.
  2. covarSampMatrix, covarPopMatrix and corrMatrix with no arguments: the state writes one moment per pair of arguments and the stream carries no count field, so SELECT length(groupUniqArray(s)) FROM (SELECT covarPopMatrixState() AS s FROM numbers(3)) aborts for all three.

I will write a one-byte placeholder in serialize for those degenerate states, with the symmetric read in deserialize, as AggregateFunctionNothing already does for a state that holds no data and ColumnTuple and IColumnDummy do for an empty tuple ("serialization into zero number of bytes is ambiguous"). The byte is written only when the range or the argument list is empty, so the state format of every non-empty range and of every matrix with at least one argument is unchanged, and both keep returning [] as they do today.

If you would rather reject an empty -Resample range and a zero-argument matrix function at creation, I will do that instead.

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]>
@groeneai groeneai changed the title Fix an assertion on aggregate function states that serialize to zero bytes Reject aggregate function parameterisations whose state serializes to zero bytes Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
this head), plus my own cold review of the resulting code, which produced 4 findings. Two earlier
rounds on this branch reviewed the approach the ruling replaced, and are superseded by it.

# Sev Finding Verdict Evidence / action
1 ⚠️ Issue #119727 was linked only inside the description template's HTML comment, so it rendered nowhere. It is an open report of this exact class, by a member, its reproducer is the parameterisation this change rejects, and its stated expectation is a refusal at INSERT or CREATE TABLE AGREE, fixed in the description Visible Related: lines for #119727 and #119700. Related: and not Closes: on purpose: this removes the producers, while the NativeReader asymmetry that report documents stays open there
2 ⚠️ The Backward Incompatible Change entry named the new exceptions but omitted the one consequence an upgrading user has to act on, that a column whose type names a rejected parameterisation no longer loads. The draft leaned on the two checks this constructor already performs, which does not carry: step == 0 and total > max_elements were never constructible, so no stored column can name them, while an empty range was AGREE, fixed in the description The entry now states it and says to drop such a column before upgrading. I make no claim about DROP on a table that fails to load, having not measured it
3 💡 The audit of the remaining aggregate functions, promised in my earlier comment, was carried out but reported nowhere public AGREE, fixed in the description One sentence: of the 96 serialize overrides in src/AggregateFunctions/, these two were the only unguarded ones
4 💡 My own enumeration puts the census at four latent shapes, not two. -Tuple over an empty tuple (Combinators/AggregateFunctionTuple.cpp:480) and categoricalInformationValue() at arity 0 (AggregateFunctionCategoricalInformationValue.cpp:116, whose sizeOfData() underflows to zero) serialize to zero bytes by the same mechanism. Both are already rejected, at AggregateFunctionTuple.cpp:648 and AggregateFunctionCategoricalInformationValue.cpp:167, but by arity checks written for unrelated reasons AGREE, fixed in the description No code change, since neither is reachable. Named in the description so the census is not narrower than the tree supports. I added no comment at either site, neither being touched here

Severity: ❌ blocker / ⚠️ major / 💡 nit. All four findings are in the description, which this phase
owns and finalizes, so no source or test file changed during review and the pre-review source
fingerprint verifies clean. Nothing was deferred.

Two checks that produced no finding, recorded because they are the ones worth doubting. Completeness:
I enumerated the carriers before reading the plan, over all 96
serialize(ConstAggregateDataPtr, WriteBuffer &, optional<size_t>) overrides in src/ and 67 inner
state helpers, and computed total for every literal <fn>Resample(begin, end, step) in tests/,
docs/, src/, programs/, utils/ and benchmark/, taking the last three parameters so forms like
topKResample(10, 1, 2, 42) are included: 216 non-degenerate call sites, and degenerate ranges in
exactly the three test files updated here. And an honest negative from the mutation matrix, which I
confirmed: once these parameterisations are rejected, no shipped statement can detect deletion of the
three chassert(!serialized.empty()) sites, because the fix closes the only path that reached them.
Those three lines are byte-identical to master and outside this diff.

Session id: cron:clickhouse-review-slot-9:20260913-215900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no randomization needed. SELECT length(countResampleMergeDistinct(10, 5, 1)(s)) FROM (SELECT countResampleState(10, 5, 1)(number, number) AS s FROM numbers(10) GROUP BY number); aborts a base debug binary with Logical error: '!serialized.empty()' on every run, and so does SELECT length(groupUniqArray(s)) FROM (SELECT covarSampMatrixState() AS s FROM numbers(3));. Both now fail with a clean exception at function creation.
b Root cause explained? Yes. -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. AggregateFunctionVarianceMatrixData::serialize writes one moment per argument pair with no count field, and the creator validated argument types but never arity, so the three matrix functions were accepted with zero arguments. Measured on base: CAST('' AS AggregateFunction(countResample(10, 5, 1), UInt64, UInt64)) yields a state of exactly 0 bytes.
c Fix matches root cause? Yes, at the producers, and no band-aid. Nothing is relaxed: all three chassert(!serialized.empty()) sites are byte-identical to master again. A marker byte was rejected because docs/.../architecture.mdx:151 requires backward compatibility for any change to an aggregate state's serialized format and no state version can supply it (a version 0 state is still zero bytes); making serialize throw was rejected because the failure would then depend on max_bytes_before_external_group_by.
d Test intent preserved / new tests added? 05210 is rewritten as a rejection test: both spellings of an empty range, the state-type spelling, the zero-argument matrix case, and two value controls (countResample(1, 5, 1) and the boundary countResample(4, 5, 1)). Three existing tests keep their purpose: 02931 still pins that a degenerate range must not reach the arena (it can no longer reach it at all); 02427 is split rather than annotated, so the MSan coverage of its non-degenerate -State half survives with a byte-identical reference line (98578 bytes, md5 2a60f2fb4ff9bb2a4733257037318b7e); 03594 still asserts these functions do not fall over on empty arguments, since a clean exception is not falling over.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (base 13263a4d..., fix 3c07bc30...), with SELECT lower(buildId()) asserted on both servers. All four tests fail on base (0 passed / 4 errors) and every annotated statement is named individually by the runner: three server error 69 was expected plus one 42 in 05210, three 42 in 03594, one 69 each in 02931 and 02427. All four pass on fix, and 200/200 randomized runs are green.
f Fix is general across code paths? Yes. -Resample is constructed only at Combinators/AggregateFunctionResample.cpp:61 and :83, both inside transformAggregateFunction, so one constructor check covers a query, an AggregateFunction type string (measured), arrayReduce, initializeAggregation and getNormalizedStateType. AggregateFunctionVarianceMatrix is in an anonymous namespace, referenced nowhere outside its TU, and that TU's only construction site is inside the creator now carrying the check; its second constructor is reachable from nothing. All 13 registered combinators were audited: those adding framing cannot be empty, those forwarding verbatim inherit the fix.
g Fix generalizes across inputs? Yes. The rejection is on the parameterisation, so argument types cannot evade it. Both spellings of an empty range ship; the smallest surviving range (total == 1) is a shipped control; all three matrix kinds are exercised. Nested and wrapped -Resample forms still pass (05031, 05055, 01159's topKResample(10, 1, 2, 42)), and a whole-tree census of all 94 literal Resample(begin, end, step) triples in tests/ and docs/ found no other degenerate call.
h Backward compatible? No, deliberately, and that is why the changelog category is Backward Incompatible Change with an entry naming exactly what starts throwing. It is the same class of decision the same constructor already makes for step == 0 and for too many elements, including that a column type naming such a parameterisation fails to load. No format, layout, setting or protocol change, so no SettingsChangesHistory.cpp entry applies.
i Invariants and contracts preserved? Yes. The change only widens a constructor precondition; nothing runs after the throw, so no state is half-built (create() is never reached and the object never becomes visible to the factory). The invariant the assertion states is now true by construction rather than by assumption, and mutation arms M2/M3 confirm the assertion is live code (deleting either rejection makes it fire again) while M4 pins the predicate and M5 is reddened by the boundary control.

Session id: cron:clickhouse-impl-slot-40:20260913-212200

@groeneai

Copy link
Copy Markdown
Collaborator Author

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 docs/resources/develop-contribute/introduction/architecture.mdx:151 requires backward compatibility for any such change, because AggregatingMergeTree persists these states. A state version cannot supply it either: a version 0 state is still zero bytes and legacy columns are pinned at version 0, so the abort would stay reachable for exactly the data the version protects. Rejecting the parameterisation changes no format at all, and all three chassert(!serialized.empty()) sites are byte-identical to master again.

The audit I promised is done: of the 96 serialize overrides in src/AggregateFunctions/, those two were the only ones able to write zero bytes without a guard. -Tuple over an empty tuple and categoricalInformationValue() at arity 0 are the same shape, and existing arity checks already reject both.

The category is now Backward Incompatible Change: countResample(10, 5, 1) and covarPopMatrix() returned [] and now throw, a column whose type names such a parameterisation no longer loads, and three existing tests needed one annotation each, keeping their original purpose. #119727 reports the same class through four persistence engines and asks for exactly this refusal, so I linked it as related.

@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-ci labels Sep 13, 2026
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fast test caught a collision on this branch that I owe you the measurement for. 05211_backup_log_zero_byte_data_file, a test of mine that merged two days ago, builds its fixture from countResample(10, 5, 1), so this branch made its first CREATE TABLE throw ARGUMENT_OUT_OF_BOUND. Pushed faf29df2f9fd2, with master merged in, since that test only exists on the branch after the merge.

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 Nothing-typed column cannot be stored, and Log implements no ADD COLUMN, so after this change nothing reachable from SQL leaves a Log family table's first data file empty while the table holds rows. StorageLog::backupData's emptiness predicate therefore stays in as defence but is no longer pinned by a test; an internal review round flagged exactly that, and I could not build a fixture for it. What remains of the test still loses its reads to FILE_DOESNT_EXIST on a binary without the BackupImpl::copyFileToDisk half of that fix, and passes 50 out of 50 runs with randomization on one that has it.

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

Amazing. Thank you!

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 5ea1812 Sep 19, 2026
177 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — title/description suggestions:

Description (currently incomplete):

  • Why: The last sentence of the body is cut off mid-clause: "-Resample already throws ARGUMENT_OUT_OF_BOUND for step == 0 and for too many elements, so neither ". The body also does not mention that 05211_backup_log_zero_byte_data_file.sh was rewritten onto Array(UInt64) and lost its two TinyLog cases, which is the largest reviewer-visible change in the diff after the two guards.

  • Suggested addition:

    Finish the truncated sentence, and add: 05211_backup_log_zero_byte_data_file.sh now reaches the zero-byte Log data file through an Array(UInt64) column whose arrays are all empty (s.bin stays empty next to a populated s.size0.bin) because the aggregate state it used is no longer constructible. The two TinyLog cases that needed the zero-byte file to be the table's first/only data file are dropped — an Array column always writes .size0.bin, so that shape has no remaining constructor.

Ignore if intentional.

leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Oct 27, 2026
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 comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-backward-incompatible Pull request with backwards incompatible changes pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants