Skip to content

Do not read a short uniqTheta state past its buffer - #119598

Merged
alexey-milovidov merged 13 commits into
masterfrom
fix-uniq-theta-short-state-oob-read
Oct 3, 2026
Merged

alexey-milovidov merged 13 commits into
masterfrom
fix-uniq-theta-short-state-oob-read

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 12, 2026 •

Copy link
Copy Markdown
Member

A uniqTheta state shorter than 24 bytes was read past the end of its buffer while being parsed - an ASan heap-buffer-overflow - and the out-of-bounds bytes then decided the size the parser reported as missing, so the same query answered differently from run to run:

SELECT CAST(char(8, 0, 1, 3, 0, 0, 0, 0, 0), 'AggregateFunction(uniqTheta, UInt64)');
-- Code: 246. Cannot deserialize Theta sketch state: at least 86160 bytes expected, actual 8
-- Code: 246. Cannot deserialize Theta sketch state: at least 2072 bytes expected, actual 8

compact_theta_sketch_parser::parse verifies that the buffer holds 8 bytes and then reads header fields that lie beyond them before it checks the size again: num_entries at offset 8 for serial versions 1, 2 and 3, and theta at offset 16 for serial versions 1 and 2. ThetaSketchData::read hands the parser the exact size, so the state is rejected - but only after those reads have already happened, and any CAST from a string can hand it a buffer of 8 bytes.

This change computes, from the first 8 bytes the parser does check for, how many bytes it is going to read before it checks the size again - 24 for serial version 1, 16 or 24 for serial version 2 depending on the preamble, 16 for a non-empty serial version 3 state whose preamble does not make the parser check on its own - and refuses a shorter state with the parser's own at least N bytes expected, actual M wording before handing it over. This is what the std::istream deserializer of datasketches does implicitly, since it has to consume those preamble bytes before it can decide anything. The upstream fix is to move each check_memory_size before the field it guards; the pre-check keeps the read in bounds for every version of datasketches-cpp this repository pulls in.

An earlier revision padded the buffer with zeros instead. That kept the reads in bounds, but it also made an 8-byte serial version 2 state with two preamble longs read num_entries as zero and pass as an empty sketch, which accepted malformed input with a wrong result. The test pins that this state is refused now. A state still cannot be refused for being shorter than 24 bytes as such: a sketch holding one entry serializes to 16 bytes and is valid, which the test also covers.

The test asserts the size each state reports as missing, which is the part that used to come from outside the buffer. Serial versions 2 and 4 compare the seed hash in the header against the one they compute, so of the four states the fuzzer produced - whose seed hash is zero - only the serial version 1 and 3 ones are refused for their size. The test therefore also covers states carrying the seed hash of the default seed, which reach each of the six reads that happen before the size is checked:

compact_theta_sketch_parser_impl.hpp:93  num_entries  serial version 1
compact_theta_sketch_parser_impl.hpp:94  theta        serial version 1
compact_theta_sketch_parser_impl.hpp:109 num_entries  serial version 2, two preamble longs
compact_theta_sketch_parser_impl.hpp:119 num_entries  serial version 2, three preamble longs
compact_theta_sketch_parser_impl.hpp:120 theta        serial version 2, three preamble longs
compact_theta_sketch_parser_impl.hpp:83  num_entries  serial version 3, two preamble longs

Found by the AST fuzzer on an unrelated pull request (#116647, AST fuzzer (arm_asan_ubsan), STID 1740-4c22).

Closes: #119595
Related: #116647

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix an out-of-bounds read when deserializing a uniqTheta state shorter than 24 bytes, for instance from CAST(<string> AS AggregateFunction(uniqTheta, ...)).


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

Version info

  • Merged into: 26.10.1.1412-master (included in 26.10 and later)
  • Backported to: 26.9.10.3, 26.8.17.3, 26.7.21.3, 26.3.42.3

`compact_theta_sketch_parser::parse` verifies that the buffer holds 8 bytes and
then, for serial versions 1, 2 and 3, reads `num_entries` at offset 8 and `theta`
at offset 16 before it checks the size again. `ThetaSketchData::read` hands it
the exact size, so a short state is rejected - but only after those reads have
already happened, and any `CAST` from a string can hand it 8 bytes:

    SELECT CAST(char(8, 0, 1, 3, 0, 0, 0, 0, 0), 'AggregateFunction(uniqTheta, UInt64)');
    -- Cannot deserialize Theta sketch state: at least 86160 bytes expected, actual 8
    -- Cannot deserialize Theta sketch state: at least 2072 bytes expected, actual 8

An ASan build reports the read as a heap-buffer-overflow; a release build spells
whichever size the neighbouring bytes happen to hold, which is why the same query
answers differently from run to run.

Pad the buffer to the largest offset the parser reads before validating anything,
while still declaring the true length to it: the premature header reads stay
inside the allocation and the parser's own size check rejects the state. The
upstream fix is to move each `check_memory_size` before the field it guards; the
padding is what keeps the read in bounds for every version of `datasketches-cpp`
this repository pulls in.

Found by the AST fuzzer on an unrelated pull request (#116647, STID 1740-4c22).

Closes: #119595
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8f81caf]

Summary: ✅


AI Review

Summary

The PR hardens ThetaSketchData::read against short uniqTheta states by deriving, from the first 8 header bytes, the minimum span datasketches::compact_theta_sketch::deserialize can touch before its own size checks run. That matches the pinned datasketches-cpp parser branches for serial versions 1–3, avoids both the original out-of-bounds read and the earlier "pad with zeros" false-acceptance case, and the new stateless test covers the unsafe header combinations plus normal round-trips. I do not see a remaining correctness issue in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 8f81caf.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.60% 79.50% -0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). labels Sep 12, 2026
alexey-milovidov and others added 4 commits September 12, 2026 08:40
The Fast test build is compiled without `datasketches`, so every query in the
test failed with `Function with name 'uniqTheta' does not exist`
(`UNKNOWN_FUNCTION`). That failure also dropped every other job in the
workflow, including the `Bugfix validation` the `new_tests_check` hook requires,
so `Finish Workflow` failed as well.

Every other `uniqTheta` test carries this tag.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… validates

The test only reached one of the reads the fix makes safe. Serial versions 2, 3
and 4 compare the seed hash in the header against the one they compute, and all
four states the fuzzer produced carry a zero seed hash, so those three stopped
at `check_seed_hash` and never got as far as `num_entries`. Only serial version
1 computes the seed hash itself instead of comparing it, which is why it was the
only state that read past its buffer at all.

Put the seed hash of the default seed in the header - `204, 147` at offset 6 -
so the states get past that check. An ASan build then reports a
heap-buffer-overflow at each of the four reads that happen before the size is
checked, rather than only the two in serial version 1:

  compact_theta_sketch_parser_impl.hpp:93  `num_entries`, serial version 1
  compact_theta_sketch_parser_impl.hpp:94  `theta`,       serial version 1
  compact_theta_sketch_parser_impl.hpp:109 `num_entries`, serial version 2, two preamble longs
  compact_theta_sketch_parser_impl.hpp:119 `num_entries`, serial version 2, three preamble longs
  compact_theta_sketch_parser_impl.hpp:120 `theta`,       serial version 2, three preamble longs
  compact_theta_sketch_parser_impl.hpp:83  `num_entries`, serial version 3, two preamble longs

The test now prints the size each state reports as missing instead of only
whether it was rejected, because that size is the part that used to come from
outside the buffer. Two of the new states report `16` rather than `24`, which
only the padded buffer makes reproducible.

One of them, serial version 2 with two preamble longs, is accepted as an empty
sketch: with `num_entries` read as zero the parser returns before it looks at
any entry. That is what the padding decides, and it is deliberate - refusing
every state below twenty-four bytes is not an option, since a single-entry
sketch is sixteen bytes long and a valid one. The test pins both this and the
sizes of the short states a `uniqTheta` aggregation really writes, so that a
future minimum-size check cannot silently reject them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Both comments claimed that keeping the declared size exact means a short state
is "still rejected". That is not quite what happens, and the test now shows the
one case where it does not: a serial version 2 state with two preamble longs
reads `num_entries` as zero, which describes an empty sketch, so the parser
returns before it looks at any entry and the state is accepted as empty. That
is what the zero padding decides, and it is the reproducible half of a choice
that used to depend on whatever followed the allocation.

Also correct the offsets the comment attributes to each serial version - `theta`
at offset 16 is read ahead of its size check by versions 1 and 2, not by
version 3, which checks for 24 bytes before reading it - and say why a state
below the padding cannot simply be refused: a sketch holding one entry is 16
bytes long and valid.

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

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8f81caf69 with master f86ca42b6 (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, 36 s compile time in total, 8 of them have a recent master baseline.

Job report

alexey-milovidov and others added 2 commits September 14, 2026 01:58
Padding the buffer to 24 bytes kept the premature header reads of
`compact_theta_sketch_parser::parse` in bounds, but it also let a
truncated state pass: a serial version 2 state with two preamble longs
and only 8 bytes read `num_entries` from the synthetic zeros and was
accepted as an empty sketch, where the `std::istream` deserializer of
`datasketches` - which has to consume the second preamble long first -
rejects it. Malformed `AggregateFunction(uniqTheta, ...)` input was thus
accepted with a wrong result, as the AI review pointed out.

Compute instead, from the first 8 bytes the parser does check for, how
many bytes it reads before it checks the size again - 24 for serial
version 1, 16 or 24 for serial version 2 depending on the preamble, 16
for a non-empty serial version 3 state whose preamble does not make the
parser check itself - and refuse a state shorter than that with the
parser's own `at least N bytes expected, actual M` wording before it is
handed over. The buffer is no longer padded, and its true size is the
only one the parser sees.

The test now expects `char(8, 2, 2, 3, 0, 0, 0, 204, 147)` to be refused
for its size, and `char(8, 0, 3, 3, 0, 0, 0, 0, 0)` as well, since the
size is validated before the seed hash is compared. It also runs its
queries through `clickhouse-client` against the running server instead
of starting `clickhouse-local` ten times, which took 37 seconds each
under MSan and failed the flaky check with `Test runs too long`; the
final three aggregations are folded into one query. It takes 2.4
seconds locally now.

Reports: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119598&sha=02d2a990b0c143c15bf94cc872c4914265eb465d&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20flaky%20check%29
PR: #119598

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119598&sha=f80bfe34e8991dc9e1c70d238bc8545b49dd977a&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 (Upgrade check (amd_release): 1 mutations could not be killed before the upgrade - a lightweight UPDATE on test_7.t_lightweight_mut_3 stuck with parts_to_do: 2) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is unrelated to this PR, which only touches uniqTheta state deserialization; CIDB shows the same failure on about a dozen other PRs from 2026-09-20 to 2026-10-01.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

The KILL MUTATION did throw: the stress-phase server (26.9.2.8) answered Code: 242 ... Table is in readonly mode (replica path: /clickhouse/tables/test_7/t_lightweight_mut_3/replicas/1) at 17:19:24, and the harness's ||: discarded it.

Why the replica was read-only: at 17:13:59 03049_unknown_identifier_materialized_column.sql ran DROP DATABASE IF EXISTS test_7, which in the stress run is the runner's shared database. DROP DATABASE calls flushAndPrepareForShutdown() on every table first and drops them one by one afterwards. Here it stopped with Code: 630 ... Cannot drop or rename test_7.table_for_dict ..., because some tables depend on it: test_7_1.dict1. (HAVE_DEPENDENT_OBJECTS), so the tables it had not reached yet, including t_lightweight_mut_3, stayed attached and read-only until restarted (the limbo state noted here).

Fixes:

The server-side cause is still on master: after a refused DROP DATABASE, the remaining ReplicatedMergeTree tables reject INSERT and KILL MUTATION with TABLE_IS_READ_ONLY until SYSTEM RESTART REPLICA (reproduced on 26.10.1.1; open issues #62933 and #120643, no PR yet). I'll send a separate PR so that a refused DROP DATABASE leaves the remaining tables usable, and link it here.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

The separate PR is #123694: DROP DATABASE now runs the checks that can refuse it for every table before preparing any table for shutdown, so a refused statement drops nothing and leaves the remaining tables writable.

@alexey-milovidov alexey-milovidov added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Oct 3, 2026

@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 and good for backport.

This is a workaround for a bug in Apache Datasketches. Should we fix it there?

@alexey-milovidov alexey-milovidov self-assigned this Oct 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 3, 2026
Merged via the queue into master with commit c8e8db5 Oct 3, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-uniq-theta-short-state-oob-read branch October 3, 2026 17:47
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 3, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 3, 2026
Backport #119598 to 26.8: Do not read a short `uniqTheta` state past its buffer
clickhouse-gh Bot added a commit that referenced this pull request Oct 3, 2026
Backport #119598 to 26.9: Do not read a short `uniqTheta` state past its buffer
clickhouse-gh Bot added a commit that referenced this pull request Oct 3, 2026
Backport #119598 to 26.7: Do not read a short `uniqTheta` state past its buffer
alexey-milovidov added a commit that referenced this pull request Oct 3, 2026
Resolve the conflict in `src/AggregateFunctions/ThetaSketchData.h`: 26.3 does not
have the `try`/`catch` around `compact_theta_sketch::deserialize` that master has,
so keep the 26.3 structure and add only the header size check of #119598 before
the call, together with the `Common/Exception.h` include and the `CORRUPTED_DATA`
error code declaration it needs. The `compact_theta_sketch_parser::parse` code in
the `datasketches-cpp` version pinned on 26.3 is identical to the one on master,
so the offsets in `headerBytesReadBeforeSizeCheck` apply unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll2 added a commit that referenced this pull request Oct 3, 2026
Cherry pick #119598 to 26.3: Do not read a short `uniqTheta` state past its buffer
robot-clickhouse added a commit that referenced this pull request Oct 3, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 3, 2026
PedroTadim added a commit that referenced this pull request Oct 4, 2026
Backport #119598 to 26.3: Do not read a short `uniqTheta` state past its buffer
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 5, 2026
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Oct 5, 2026
…cpp` fix

Update `contrib/datasketches-cpp` to a revision where
`compact_theta_sketch_parser::parse` checks that the buffer holds the whole
preamble before it reads a field from it, and remove the workaround in
`ThetaSketchData::read` that computed the same bound ahead of the parser.

The parser compares the seed hash of a serial version 3 state before it
checks the size, so a short serial version 3 state with a wrong seed hash
is now refused with `seed hash mismatch` instead of a size message.

Related: ClickHouse#119598
Related: apache/datasketches-cpp#536

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 9, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

uniqTheta state shorter than 24 bytes is read past its buffer (ASan heap-buffer-overflow in compact_theta_sketch_parser::parse)

4 participants