Skip to content

Fix abort on malformed uniqTheta state in ThetaSketchData::read - #106260

Merged
Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-106259-uniqtheta-deserialize-sigabrt
Jun 8, 2026
Merged

Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-106259-uniqtheta-deserialize-sigabrt

Conversation

@groeneai

@groeneai groeneai commented Jun 1, 2026 •

Copy link
Copy Markdown
Collaborator

The datasketches library throws std::out_of_range / std::invalid_argument when deserialising malformed Theta sketch bytes. Those are not DB::Exception, so they escape SerializationAggregateFunction's catch (...) block (which rethrows by type) and ReplaceQueryParameterVisitor (catch (Exception &)). At the top level a bare std::logic_error subclass triggers an unconditional abortOnFailedAssertion and SIGABRT, in both debug and release builds.

Wrap the datasketches::compact_theta_sketch::deserialize call at the library boundary in ThetaSketchData::read with a try / catch block that rethrows DB::Exception unchanged and translates bare std::exception to DB::Exception(CORRUPTED_DATA). Both the RowBinary deserializeBinary path and the query-parameter deserializeTextEscaped path go through this read, so a single boundary catches both fuzzer-found code paths.

Adds stateless regression test 04307_uniqTheta_corrupted_state_106259 covering both code paths with the 24-byte payload from the issue.

Closes #106259

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 into CHANGELOG.md):

Fixed an abort when deserialising a malformed AggregateFunction(uniqTheta, ...) state from RowBinary input or a query parameter. The bad input is now rejected with CORRUPTED_DATA instead of escaping as a std::exception and aborting the process via abortOnFailedAssertion.

Documentation entry for user-facing changes

  • Documentation is not required: the change only converts an internal abort into a user-facing exception.

Version info

  • Merged into: 26.6.1.495

Deserializing a malformed AggregateFunction(uniqTheta, ...) state used
to throw std::out_of_range / std::invalid_argument from the third-party
datasketches library. Those are not DB::Exception, so they escaped the
catch (...) block in SerializationAggregateFunction (which rethrows by
type) and ReplaceQueryParameterVisitor (which only catches DB::Exception).
At the top level a bare std::exception is treated as LOGICAL_ERROR
(code 1001), and abortOnFailedAssertion aborts the process with SIGABRT.

Wrap the datasketches::compact_theta_sketch::deserialize call at the
library boundary in ThetaSketchData::read with a try / catch block that
re-throws DB::Exception unchanged and translates bare std::exception to
DB::Exception(CORRUPTED_DATA). Both the RowBinary deserializeBinary path
and the query-parameter deserializeTextEscaped path go through this read,
so a single boundary catches both fuzzer-found code paths.

Adds a stateless regression test 04307_uniqTheta_corrupted_state_106259
covering both code paths with the 24-byte payload from the issue.

Closes ClickHouse#106259
@groeneai

groeneai commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (TASK.md Phase 4 Step 9):

(a) Deterministic repro? Yes. printf '\x03\x03\x03\x30\x00…' | clickhouse-local --input-format=RowBinary --structure='x AggregateFunction(uniqTheta, IPv6)' -q 'SELECT x FROM table' aborts on every invocation with the pre-fix binary (exit 134, no stderr).

(b) Root cause explained? Yes. The 3-byte sketch payload is shorter than the Theta sketch minimum, so datasketches::compact_theta_sketch_parser::check_memory_size throws std::out_of_range. That is a std::logic_error subclass, not a DB::Exception. SerializationAggregateFunction::deserializeBinary and deserializeFromString only catch (...) and rethrow by type, so the std::out_of_range stays a std::out_of_range. It bubbles past ReplaceQueryParameterVisitor (catch (Exception &)) and reaches getCurrentExceptionMessageAndPattern, which has a catch (const std::logic_error &) arm that calls abortOnFailedAssertion unconditionally, regardless of abort_on_logical_error.

(c) Fix matches root cause? Yes. The translation happens at the third-party library boundary in ThetaSketchData::read. The catch (const DB::Exception &) { throw; } arm preserves ClickHouse exceptions (memory limits, etc.) unchanged; the catch (const std::exception &) arm translates the library failure to DB::Exception(CORRUPTED_DATA). No assertion is weakened, no broad no-random-* tag is added.

(d) Test intent preserved / new tests added? Yes. New stateless test 04307_uniqTheta_corrupted_state_106259.sh covers the two crash paths from the issue (RowBinary input and query parameter). No existing test was relaxed.

(e) Both directions demonstrated? Yes:

  • pre-fix binary: bash tests/queries/0_stateless/04307_uniqTheta_corrupted_state_106259.sh -> FAIL rowbinary / FAIL param (grep does not find CORRUPTED_DATA because the process aborted before producing stderr)
  • post-fix binary: OK rowbinary / OK param
  • direct repro post-fix: Code: 246. DB::Exception: Cannot deserialize Theta sketch state: at least 8 bytes expected, actual 3 … (CORRUPTED_DATA); exit 246

(f) Fix is general, not a narrow patch? Yes. The fix is at the only ClickHouse call site into datasketches::compact_theta_sketch::deserialize. Both fuzzer-found paths (deserializeBinary for RowBinary, deserializeTextEscaped for query parameters) funnel through ThetaSketchData::read, so one boundary catches both. Sibling aggregate sketches (uniqHLL12, quantileTDigest, DDSketch) do not use the datasketches library and already produce clean DB::Exception on malformed input (verified in the issue body table). StatisticsCountMinSketch::deserialize does call datasketches::count_min_sketch::deserialize and likely has the same bug class, but I do not have a local repro for it; per @Algunenano directive on speculative defensive fixes, I am not touching it in this PR. Flagged as a follow-up candidate.

Session: cron:clickhouse-ci-task-worker:20260601-210000

@groeneai

groeneai commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @qoega for the directive. The fix translates the datasketches std::exception at the ThetaSketchData::read boundary into DB::Exception(CORRUPTED_DATA), with regression test for both the RowBinary and query-parameter paths.

@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f9394fc]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Logical error: Coordination mode mismatch for stream A: got B, expected C (STID: 6117-68e9) FAIL cidb, issue

AI Review

Summary

This PR fixes malformed AggregateFunction(uniqTheta, ...) state deserialization by translating third-party datasketches parse exceptions in ThetaSketchData::read into CORRUPTED_DATA, while preserving existing DB::Exception behavior and rethrowing std::bad_alloc. The added regression test covers both the RowBinary and query-parameter paths described in the linked issue. I found no unresolved correctness findings.

Missing context / blind spots
  • ⚠️ I could not run the stateless test locally because this checkout has no build* directory or clickhouse binary; a passing CI run closes this gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 1, 2026
The previous commit translated every std::exception from
`compact_theta_sketch::deserialize` into `CORRUPTED_DATA`. The
`std::exception` base also covers `std::bad_alloc` from internal
allocations in `deserialize`, `getSkUnion`, or `theta_union.update`,
so a valid large state or a memory-pressure failure would have been
mis-reported as data corruption.

Add a `catch (const std::bad_alloc &) { throw; }` arm before the
catch-all so allocation failures propagate as allocation failures.
Malformed-input paths still throw `std::invalid_argument` /
`std::out_of_range`, which the catch-all keeps translating to
`CORRUPTED_DATA`. The existing regression test
`04307_uniqTheta_corrupted_state_106259.sh` still passes for both
the RowBinary and query-parameter paths.

Addresses clickhouse-gh[bot] inline review on
ClickHouse#106260
@clickhouse-gh

clickhouse-gh Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.50% +0.10%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.10% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 14/16 (87.50%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finished on f9394fc. The only test-level failure is unrelated to this PR:

  • Stress test (arm_debug) -- Logical error: Coordination mode mismatch for stream A: got B, expected C (STID 6117-68e9): pre-existing flaky parallel-replicas coordination issue, observed across 15+ unrelated PRs in the last 30 days (104591, 105335, 106257, 100399, 106028, 106227, 105703, 106025, 106048, 105840, 105354, 98856, 96886, ... and master). Tracked separately as a chronic flaky test; not introduced by this PR (this PR only touches ThetaSketchData::read exception translation). The "PR" and "Report messages" aggregator checks just reflect that one stress failure.

All other 144 checks pass. The fix + regression test (04307_uniqTheta_corrupted_state_106259) are green.

@Algunenano Algunenano self-assigned this Jun 8, 2026

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

Looks good:

Code: 1001. DB::Exception: std::out_of_range: at least 8 bytes expected, actual 3. (STD_EXCEPTION)
Code: 246. DB::Exception: Cannot deserialize Theta sketch state: at least 8 bytes expected, actual 3: (in file/uri (fd = 0)): While executing BinaryRowInputFormat: While executing File. (CORRUPTED_DATA)

Not something we need to backport, it only affected debug releases

@Algunenano
Algunenano added this pull request to the merge queue Jun 8, 2026
Merged via the queue into ClickHouse:master with commit c0b4d93 Jun 8, 2026
164 of 167 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 8, 2026
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov, could you add v26.3-must-backport to this PR? The 26.3 backport of #119598 (#123773) needs it.

On 26.3, 05215_uniq_theta_short_state aborts the server in Stress test (amd_tsan) (report) on SELECT finalizeAggregation(CAST(char(8, 0, 2, 3, 0, 0, 0, 0, 0), 'AggregateFunction(uniqTheta, UInt64)')). The std::invalid_argument ("seed hash mismatch") from check_seed_hash is a std::logic_error. Without the catch block of this PR it is not translated to CORRUPTED_DATA, so a debug or sanitizer build aborts. 26.3 was cut before this PR merged; 26.7, 26.8 and 26.9 already have it.

This PR applies cleanly to the current 26.3 (three-way merge of ThetaSketchData.h; its test is new there). It overlaps #123773 in ThetaSketchData::read, so whichever of the two merges second needs the shape master has: the size check, then the try/catch. If you prefer not to backport this PR, restoring only that catch block in backport/26.3/119598 also fixes #123773.

alexey-milovidov added a commit that referenced this pull request Oct 4, 2026
…ead`

The backported test `05215_uniq_theta_short_state` feeds states that
`datasketches` refuses with `std::invalid_argument` (`seed hash mismatch`).
On 26.3 that exception was not translated, so it reached the top level as
`LOGICAL_ERROR` and aborted the sanitizer build in the stress test. Bring in
the translation to `CORRUPTED_DATA` from #106260,
which the original change relied on.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=123773&sha=4636b5a69c3dfbb9110b7660ee1461d8f6cdf5d4&name_0=BackportPR&name_1=Stress%20test%20%28amd_tsan%29
PR: #123773

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants