Skip to content

SipHash::update: short-circuit on empty input - #106469

Merged
azat merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/separate-siphash-empty-guard
Jun 8, 2026
Merged

azat merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/separate-siphash-empty-guard

Conversation

@groeneai

@groeneai groeneai commented Jun 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #106261

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...

Description / motivation

Split out from PR #106261 per @azat: keep the user-visible bug fix (out-of-range IntervalKind binary decoding) on PR #106261 so it can be backported, and isolate this defense-in-depth tweak to SipHash::update here.

SipHash::update(const char * data, UInt64 size) evaluates data + size and data + 8 early in the unrolled loop. When data == nullptr and size == 0, the loop body never runs (nullptr + 8 <= nullptr is false) but evaluating data + 8 on a null pointer with non-zero offset is UB per [expr.add]/4. UBSan flags it under -fsanitize=pointer-overflow.

The triggering path that surfaced this (STID 3285-3bba) was SerializationInterval::getHash -> SipHash::update(std::string_view) -> update(sv.data(), sv.size()) with an empty view whose data() == nullptr (libcxx behaviour for magic_enum::enum_name on an unknown enum value). That specific path is closed at the deserialization site by PR #106261. This PR is the narrow precondition: an empty input is a no-op.

ALWAYS_INLINE keeps the hot path unchanged for non-empty inputs and the size==0 branch folds away for callers that pass a constant non-zero size. Any future caller that hands SipHash::update a (nullptr, 0) pair (e.g. an empty std::string_view from another magic_enum-style source) will be a no-op instead of re-tripping UBSan.

Tests

src/Common/tests/gtest_sip_hash.cpp:

  • UpdateWithEmptyStringViewDoesNotInvokeUB: hashing with an empty std::string_view followed by other data and a final empty update does not invoke UB and produces a stable digest. UBSan unit test target catches the original report on master.
  • UpdateWithEmptyStringViewIsNoOp: empty updates are observably no-ops; the digest equals what you would get hashing the same payload without the empty prefix/suffix updates.

cc @azat

Version info

  • Merged into: 26.6.1.523

`SipHash::update(const char * data, UInt64 size)` evaluates `data + size`
and `data + 8` near the start of the unrolled loop. When `data == nullptr`
and `size == 0`, the loop body never executes (the condition
`nullptr + 8 <= nullptr` is false), but evaluating `data + 8` on a null
pointer with non-zero offset is UB per `[expr.add]/4`. UBSan flags this
under `-fsanitize=pointer-overflow`.

The trigger surfaced via `SerializationInterval::getHash` ->
`SipHash::update(std::string_view sv)` -> `update(sv.data(), sv.size())`
when an out-of-range `IntervalKind` produced an empty `std::string_view`
with `data() == nullptr` from `magic_enum::enum_name` on libcxx
(STID 3285-3bba in the AST fuzzer). The primary fix for that specific
path lives in PR ClickHouse#106261 (range check at the deserialization site).

This change is a narrow precondition for `SipHash::update`: an empty
input is a no-op. `ALWAYS_INLINE` keeps the hot path unchanged for
non-empty inputs and the single zero-size branch folds away for callers
that pass a constant non-zero size. Any future caller that legitimately
hands `SipHash::update` a `(nullptr, 0)` pair (e.g. an empty string_view
from another magic_enum-style source) will be a no-op instead of
re-tripping UBSan.

Adds a small gtest (`gtest_sip_hash.cpp`) that:
1. Verifies updating with an empty std::string_view followed by other
   data and a final empty update does not invoke UB and produces a
   stable digest.
2. Verifies the empty updates are observably no-ops: the digest equals
   what you would get hashing the same payload without the empty
   prefix/suffix updates.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. UBSan trips at src/Common/SipHash.h:107 (post-fix line 134 in original report) on every call to SipHash::update(const char *, UInt64) with data == nullptr and size == 0 under -fsanitize=pointer-overflow. Trigger fires unconditionally when the inputs match. STID 3285-3bba documented the specific real-world path (IntervalKind binary decoding -> empty std::string_view{nullptr, 0} from magic_enum::enum_name).
b Root cause explained? Yes. update(const char * data, UInt64 size) evaluates data + size then const char * end = data + size; then enters while (data + 8 <= end). Even though the loop body never executes (nullptr + 8 <= nullptr is false), the pointer arithmetic itself with a non-zero offset on a null pointer is UB per C++ [expr.add]/4. UBSan flags via pointer-overflow. The user-visible bug at the IntervalKind deserialization site (PR #106261) is what produces a (nullptr, 0) argument in practice.
c Fix matches root cause? Yes. The fix short-circuits at the top of SipHash::update when size == 0, removing the data + 8 evaluation entirely. This addresses the UB at its source (the function does not need a null pointer to have valid arithmetic), independent of any caller. It is intentionally NOT the user-visible fix for STID 3285-3bba: that one lives in PR #106261 (range check at the IntervalKind deserialization site, prevents the bad string_view from ever existing).
d Test intent preserved / new tests added? New tests added in src/Common/tests/gtest_sip_hash.cpp. (1) UpdateWithEmptyStringViewDoesNotInvokeUB exercises empty std::string_view{} updates intermixed with data and asserts no UBSan trip. (2) UpdateWithEmptyStringViewIsNoOp asserts that empty updates are observably no-ops by comparing the digest to the same payload without the empty prefix/suffix.
e Both directions demonstrated? Yes. Without the fix, the gtest would trip UBSan on pointer-overflow under the ASAN+UBSan unit-tests target on the pre-fix master tree. With the fix, both gtests pass. The original report was reproduced on PR #106251 CI (https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106251&sha=874c4f0fc6fa05c7726121221bd18e4185eda64e&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29) and traced into this code path during PR #106261 investigation.
f Fix is general, not a narrow patch? Yes. This fix is purely a precondition for SipHash::update: an empty input is a no-op. It does NOT mask an upstream caller bug — that caller bug is fixed at its source in PR #106261. This change protects ALL future callers from a class of UBSan trip when handing in an empty (nullptr, 0) pair. The hot path is unchanged: ALWAYS_INLINE lets the size==0 branch fold away for callers that pass a constant non-zero size, and the runtime branch is one predictable comparison for callers that pass a runtime size.

Session id: cron:clickhouse-ci-task-worker:20260604-133700

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 4, 2026
@azat asked for the SipHash defense-in-depth tweak (size==0 short-circuit
plus the gtest) to be split out of this PR so the user-visible bug fix
(out-of-range IntervalKind binary decoding -> INCORRECT_DATA) can be
backported independently.

The SipHash hunk is now PR ClickHouse#106469. This PR keeps only the IntervalKind
range check at the deserialization site plus the regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@azat azat self-assigned this Jun 4, 2026
@nihalzp nihalzp added the can be tested Allows running workflows for external contributors label Jun 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9cad85a]

Summary: ✅


AI Review

Summary

This PR makes empty input a no-op for SipHash::update and adds focused gtest coverage for empty std::string_view inputs. The direction is good, but the same pointer-arithmetic UB that motivated the change is still present for normal short buffers, so I am requesting a small follow-up change before approval.

Findings

❌ Blockers

  • [src/Common/SipHash.h:111] SipHash::update still evaluates data + 8 before proving that 8 bytes remain. This is outside the valid [data, end] range for 1-7 byte inputs, and again after the last full 8-byte chunk when data == end, so valid non-empty inputs can still hit undefined behavior. Replace the loop condition with a form that does not create an out-of-range pointer, for example while (end - data >= 8).
Final Verdict

Status: ❌ Block

Minimum required action: fix the data + 8 loop condition so SipHash::update never forms an out-of-range pointer during bounds checking.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 4, 2026
@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI is fully finished on 942d867f7f8: workflow PR completed at 2026-06-04T19:11:44Z (~50 min ago).

CI ledger for 942d867f7f8:

Failure Disposition
AST fuzzer (amd_debug, targeted) / Segmentation fault (STID 5737-6ff0) Chronic trunk fuzzer crash deep in IdentifierResolver::tryBindIdentifierToJoinUsingColumn. Cross-PR 30d: 5 distinct PRs (#100371, #104911, #105162, #106261, this PR), 0 master hits. Tracked under task 2026-05-06-ci-p0-stid-5737-6ff0-segmentation-fault. NOT PR-caused — this PR's diff is a 2-line SipHash::update size==0 short-circuit; cannot affect the analyzer's JOIN USING column resolver.
Stateless tests (amd_binary_excluded_from_llvm) / 00974_query_profiler Chronic flaky. CIDB diagnose: "Re-running with the same randomized settings (budget 60s)... Runs: 32, Failed: 0, Passed: 32. The failure is not reproducible (likely a transient issue)." Cross-PR 30d: 8 distinct PRs incl 1 master hit (#100242 2x, #105338, #104558, master, this PR, #104563, #105543). NOT PR-caused.
Mergeable Check / Report messages Reflect the two failing test entries above; not separate signals.

PR is APPROVED. Both failures are pre-existing chronic trunk issues unrelated to the SipHash size==0 short-circuit.

@azat
azat enabled auto-merge June 8, 2026 15:13
@azat

azat commented Jun 8, 2026

Copy link
Copy Markdown
Member

@groeneai merge with master please

@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator Author

@azat merged master into the branch. Merge commit: 9cad85a4ad6. No conflicts; diff vs master is unchanged (4 lines in src/Common/SipHash.h + 33 lines gtest_sip_hash.cpp).

Session: cron:clickhouse-ci-task-worker:20260608-164800

Comment thread src/Common/SipHash.h
ALWAYS_INLINE void update(const char * data, UInt64 size)
{
/// Avoid UB from `data + 8` arithmetic below when `data == nullptr`.
if (size == 0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

size == 0 only handles the nullptr, 0 trigger, but the UB root cause remains for ordinary non-empty inputs: the loop below evaluates data + 8 before checking whether 8 bytes remain. For a 1-7 byte buffer, and again after the last full 8-byte chunk when data == end, that expression is outside the valid [data, end] range, so SipHash::update still has undefined behavior on valid short inputs. Could we make the loop use pointer subtraction instead, for example while (end - data >= 8), so no out-of-range pointer is formed?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, technically correct: data + 8 is also formed when data == end after the last full chunk, and for 1-7 byte buffers when end - data < 8 on the very first iteration; both are out-of-range pointer expressions and UBSan's pointer-overflow will flag them under the right build flags.

I'd like to keep this PR narrow per @azat's split request (a 2-line size == 0 short-circuit addressing the (nullptr, 0) STID 3285-3bba trigger), so I won't widen the scope here. I'll file a separate follow-up PR rewriting the unrolled loop to use end - data >= 8 (and audit the rest of update for the same shape). Tracking it now.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filed the follow-up: #107103. It rewrites the loop condition to while (end - data >= 8) so data + 8 is never formed past end for short inputs, with byte-identical hash output and boundary-length gtest cases. Thanks for catching the general case.

@clickhouse-gh

clickhouse-gh Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.30% +0.10%

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

Full report · Diff report

@azat
azat added this pull request to the merge queue Jun 8, 2026
Merged via the queue into ClickHouse:master with commit 47bab98 Jun 8, 2026
166 checks passed
@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI fully finished on 9cad85a4ad6 (post-merge-master). Finish Workflow + Mergeable Check + PR aggregator all SUCCESS at 2026-06-08T21:38:10Z (≥20-min CIDB ingestion buffer met).

CI Ledger — covered SHA: 9cad85a

Result Notes
All 166 checks SUCCESS or SKIPPED Zero failures recorded in CIDB on this SHA
Stateless / Integration / Unit tests / Performance / Build matrix All green across all sanitizer variants and architectures

PR APPROVED by @ azat on prior SHA 942d867f7f8. The merge-master diff is the same 37-line patch (src/Common/SipHash.h +4, src/Common/tests/gtest_sip_hash.cpp +33). Awaiting merge.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 8, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 11, 2026
…d loop

The unrolled 8-byte loop used `while (data + 8 <= end)`. When fewer than 8
bytes remain (a 1-7 byte input, or the tail after the last full chunk where
data == end), `data + 8` points past the one-past-the-end pointer `end`.
Forming such a pointer is undefined behavior under [expr.add]/4, independent
of whether it is dereferenced.

This is the general form of the same defect class as the empty-input case
fixed in ClickHouse#106469: there `data` was nullptr and `data + 8` triggered UBSan's
"applying non-zero offset to null pointer"; here `data` is a valid non-null
pointer but the formed pointer still leaves the [base, base+size] range.

Rewrite the condition as `end - data >= 8`, which only ever evaluates
pointer subtraction and never forms a pointer outside the buffer. The loop
body is unchanged, so the computed hash is identical for every input length.

The `size == 0` early return added in ClickHouse#106469 is now redundant and is
removed. After the rewrite the empty input path forms no out-of-range
pointer: `end = data + size` is `nullptr + 0` (well-defined), and the only
remaining pointer arithmetic is the subtractions `end - data` (all
`nullptr - nullptr`, i.e. 0), so the loop body and the tail switch never run.
This is the same as a zero-length valid buffer. Verified under clang-21
`-fsanitize=address,undefined -fno-sanitize-recover=all`: the existing
empty-string-view tests from ClickHouse#106469 and the new boundary/chunk tests all
pass and produce byte-identical hashes with the guard removed.

Found by clickhouse-gh[bot] inline review on ClickHouse#106469.

Co-Authored-By: Claude Opus 4.8 <[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-not-for-changelog This PR should not be mentioned in the changelog 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