Skip to content

base: define wraparound in ignore-overflow helpers - #120808

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
yqtian-se:fix-ignore-overflow-wraparound
Oct 1, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
yqtian-se:fix-ignore-overflow-wraparound

Conversation

@yqtian-se

@yqtian-se yqtian-se commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #120351

The addIgnoreOverflow, subIgnoreOverflow, mulIgnoreOverflow, and
negateIgnoreOverflow helpers currently perform signed arithmetic under
NO_SANITIZE_UNDEFINED. The attribute suppresses undefined-behavior
diagnostics, but does not give signed overflow wrapping semantics.

With the current header, a probe for
addIgnoreOverflow(INT_MAX, 1) < INT_MAX returns true at -O0, but Clang 20
and Clang 22 optimize the comparison to false at -O1, -O2, and -O3.
The source and helper names require the wrapped result, and the build does not
globally use -fwrapv or -fno-strict-overflow.

For integer results, this change performs each operation in the unsigned version
of the expression's result type and converts the result back. That defines the
intended modulo arithmetic without relying on a diagnostic-suppression
attribute. Using the expression's result type also preserves integer promotion
for narrow operands. Non-integer result types, including Decimal, continue to
use their existing overloaded operators.

Validation:

  • rebased onto master at 9622a4a;
  • compared the original and patched headers under Clang 20 and Clang 22 at
    -O0, -O1, -O2, and -O3;
  • the original fails the overflow observation at every optimized level, while
    the patched header passes at all four levels;
  • the probe covers all four helpers over promoted Int8/Int16, signed
    Int32/Int64/Int128/Int256, and unsigned
    UInt32/UInt64/UInt128/UInt256;
  • the complete clickhouse target builds with the official binary-builder and
    Clang 22, including existing Decimal<Int128> and Decimal<Int256> callers;
  • git diff --check passes.

The linked issue contains the focused reproducer. I did not find an existing
direct unit-test target for arithmeticOverflow.h or a stable SQL-level trigger,
so this change relies on the focused compiler matrix and project CI.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Version info

  • Merged into: 26.10.1.1193-master (included in 26.10 and later)

The ignore-overflow helpers currently perform signed arithmetic with undefined behavior. NO_SANITIZE_UNDEFINED suppresses diagnostics but does not define wraparound, so an optimizer may use the overflow assumption.

For integer results, perform each operation in the unsigned counterpart of its result type and convert the modulo result back. This preserves integer promotion for narrow operands and defines the intended wraparound for signed and wide integer types. Keep the existing operator path for non-integer result types such as Decimal.

Signed-off-by: Yongqiang Tian <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. external Author is not a member of the ClickHouse organization labels Sep 18, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b31d724]

Summary: ✅


AI Review

Summary

This PR replaces UB-prone signed arithmetic in addIgnoreOverflow, subIgnoreOverflow, mulIgnoreOverflow, and negateIgnoreOverflow with unsigned-domain arithmetic in the helpers' result type, and adds focused gtest coverage for both same-width wraparound and promotion-sensitive narrow operands. The previous inline review concerns are addressed in the current code, and I did not find remaining correctness, safety, or coverage gaps in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit b31d724.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 19, 2026
Comment thread base/base/arithmeticOverflow.h Resolved
@yqtian-se

Copy link
Copy Markdown
Contributor Author

I’ve added a regression test and verified it locally with Clang 22. I’m not very familiar with ClickHouse’s test infrastructure, so please let me know if its placement or structure should be adjusted

@yqtian-se

Copy link
Copy Markdown
Contributor Author

Thanks, fixed in eebd4b7. The boundary operands now go through a runtime-dependent runtimeValue helper, preventing constant propagation even under LTO. I also verified that the old implementation fails at -O3 with this test shape, while the unsigned-domain implementation passes.

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 37 queries analysed

This PR rewrites the integer overflow helpers (add/sub/mul/negateIgnoreOverflow) to use unsigned-cast wraparound instead of UB-based signed arithmetic. TPC-H Q1 is dominated by summed arithmetic over many rows, so it is the one benchmark query that plausibly exercises the changed hot path, and the deterministic math flagged it as not_sure (+26.0%) rather than a locked regression. The baseline for this query is intrinsically noisy and CPU time also rose, so the delta is a real candidate worth a rerun but not a confirmed regression. No cross-query pattern: only Q1 touches the modified code path.

clickbench

🟢 No significant changes

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 50 63 +26.0% <0.0001 cpu: Q1 is arithmetic-heavy (SUM/AVG over large row counts) and this PR rewrites the mulIgnoreOverflow/addIgnoreOverflow helpers, so a CPU shift here is plausible. The baseline is noisy, so treat +26.0% as tentative.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: c2c13324-2a48-4b1f-9cbe-7993a935304a
  • MIRAI run: 66a21508-2886-472c-9dc4-5726ab2cfa29
  • PR check IDs:
    • clickbench_1040029_1789923598
    • clickbench_1040042_1789923598
    • clickbench_1040048_1789923598
    • tpch_adapted_1_official_1040059_1789923598
    • tpch_adapted_1_official_1040085_1789923598
    • tpch_adapted_1_official_1040099_1789923598

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b31d72413 with master d6021c7b4 (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.

Object file sizes

68 object files changed (+212.73 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/plus.cpp.o 9.24 MiB 9.33 MiB +96.96 KiB (+1.02%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/minus.cpp.o 8.97 MiB 9.06 MiB +83.64 KiB (+0.91%)
src/CMakeFiles/dbms.dir/DataTypes/DataTypesDecimal.cpp.o 1.51 MiB 1.45 MiB -58.42 KiB (-3.77%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/mapOp.cpp.o 3.52 MiB 3.49 MiB -32.70 KiB (-0.91%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/least.cpp.o 7.56 MiB 7.60 MiB +31.13 KiB (+0.40%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/greatest.cpp.o 7.59 MiB 7.62 MiB +31.12 KiB (+0.40%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion.cpp.o 21.36 MiB 21.38 MiB +28.66 KiB (+0.13%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

alexey-milovidov and others added 2 commits September 20, 2026 19:34
The existing cases only exercised operands whose `decltype(x op y)` is the
same type as the operands themselves, so they did not lock down the other
half of the contract: narrow operands undergo the usual integral promotions,
and the helpers must wrap in the promoted result type rather than at the
operand width.

Add `ArithmeticOverflow.IgnoreOverflowPromotedNarrowOperands`, covering
`Int16` and `UInt8` - for both, `decltype(x op y)` is `int`, which is pinned
with a `static_assert` - and asserting `int`-typed results that do not fit
back into the operand type.

A refactor that switched the helpers to `make_unsigned_t<T1>` and wrapped at
the operand width was control-proved to fail the new cases:
`subIgnoreOverflow(Int16{-32768}, Int16{1})` yields `32767` instead of
`-32769`, and `addIgnoreOverflow(UInt8{255}, UInt8{1})` yields `0` instead
of `256`.

`Int8` is `signed _BitInt(8)`, which does not promote, so it is covered by
`ArithmeticOverflow.IgnoreOverflowWraparound` instead - it is added to that
test's type list here.

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

Copy link
Copy Markdown
Member

🕵 On the not_sure TPC-H Q1 (+26.0%) item in the Cloud Performance Report: I checked whether the helper rewrite can change codegen at all, and it cannot.

I compiled a representative hot loop (acc = add(acc, mul(a[i], b[i])) over Int64) twice with -O3, once against the old NO_SANITIZE_UNDEFINED signed form and once against the new unsigned-domain form, and diffed the generated assembly. Both bodies are 42 instructions and identical instruction-for-instruction - the only difference in the listing is the // @loopOld / // @loopNew symbol comment. That is expected: two's-complement mul / add are the same machine instruction whether the operands are typed signed or unsigned; the old code only differed in what the optimizer was permitted to assume, not in what it emitted here.

So there is no mechanism by which this PR slows Q1 down, and the +26.0% is baseline noise. Note also that the Performance Comparison CI jobs were skipped on this PR (not labeled pr-performance), so that report is the only perf signal and it is explicitly marked inconclusive.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The only red on the previous head was Performance Comparison (arm_release, master_head, 5/6), flagging and_compare_chain_derived #2 as +17.1% slower (16.1ms -> 18.9ms, threshold +13.9%). This is noise on a chronically jittery query, not a regression:

  • The query does not touch the changed code. It is SELECT count() FROM t_chain_derived_join AS l INNER JOIN t_chain_derived AS r ON l.k = r.k WHERE l.v < r.k AND 9900000 < l.v - plain UInt64 columns. common::addIgnoreOverflow / subIgnoreOverflow / mulIgnoreOverflow / negateIgnoreOverflow are only reached from DecimalComparison.h, DateTimeTransforms.h and mapAdd/mapSubtract, none of which are in this plan.

  • This query's natural spread already covers the reported delta. Over the last 21 days on that exact shard (420 runs, both sides), its per-run duration is p05 14ms / p50 18ms / p95 22ms - while its neighbours in the same file are tight (#1: 44-48ms, #3: 127-140ms). Both of the reported numbers, 16.1ms and 18.9ms, sit inside the ordinary p05-p95 band.

  • It exceeds the threshold on master runs about as often as a coin flip. Across 2671 arm_release, master_head runs in the last 21 days, |new-old|/old for this query exceeds the 13.9% threshold in 1185 of them (44.4%), with a maximum of 64.3%. The comparison is master-vs-master on those runs, so every one of those excursions is pure measurement noise.

This complements the earlier assembly check for the Cloud Performance Report not_sure TPC-H Q1 item: the helper rewrite emits byte-identical code, so there is no mechanism for a slowdown in either report.

Also merged the latest master (the branch was 421 commits behind); the merge was clean and the diff against master is still exactly the two files of this pull request.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The only red on head 2f99ff899655 is Performance Comparison (arm_release, master_head, 1/6), flagging order_by_read_in_order #1 (SELECT * FROM hits_100m_single ORDER BY CounterID DESC, toStartOfWeek(EventDate) DESC LIMIT 100) as +19.9% slower (17.2 ms -> 20.7 ms) against a +19.9% threshold. It is not caused by this PR:

This is tracked in #121456 ("order_by_read_in_order #1 is the top source of slower verdicts, and none of them are regressions"); the gate fix in progress is #121090. Nothing merged on master clears it yet, so I did not re-merge master just to re-roll the shard. Everything else is green, there are 0 unresolved review threads, and the AI review verdict is Approve.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged origin/master (850 commits behind, clean, no conflicts) and pushed fe64e8388d75. The diff against master is still exactly the two PR files.

The only red on the previous head was Performance Comparison (arm_release, master_head, 1/6) flagging order_by_read_in_order #1, already refuted above as noise. Since then #121278 landed on master: it fixes the perf CI threshold learning (the per-query historical threshold was silently collapsing to the 0.15 floor when a query's display name drifted, which is exactly how noisy micro benchmarks were being reported slower on unrelated pull requests and on master). The merge pulls that fix in so the fresh run is judged by the proper thresholds. The master_head gate fix #121090 is still open.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The only red on head fe64e8388d75 is Integration tests (arm_binary, distributed plan, 3/4): test_storage_kafka/test_multi_consumer_quota.py::test_multi_consumer_with_partition_affinity failed with kafka_aff_s2_r2 never acquired any partition within 240s (report). This is a Kafka partition-assignment timing flake that cannot reach the common::*IgnoreOverflow helpers changed here; the fix is in flight in #120556 (Make test_multi_consumer_with_partition_affinity deterministic, still open). No code change needed on this PR; 0 unresolved threads.

@yqtian-se

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov,
Thanks for the continued follow-up and for helping clarify the performance results and CI failures. I really appreciate the help with this patch.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch (clean, diff still exactly the two PR files) to pull in #120556, which fixes the only red check on the previous head: the test_storage_kafka/test_multi_consumer_quota.py::test_multi_consumer_with_partition_affinity flake in Integration tests (arm_binary, distributed plan, 3/4).

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=120808&sha=5b482b107d0718ed3072ac0cc43da01ea980dc2b&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

03312_line_numbers got two extra query_log rows for its own SYSTEM FLUSH LOGS query_log, text_log (QueryStart 3 10 / QueryFinish 3 10), presumably because a concurrent flush wrote them before the SELECT read the table. Restricting the query_log query to script_query_number IN (1, 2) would make it deterministic. Rare: checks shows 2 failures in 30 days (PRs #106734 and this one). Not related to this PR, which only touches base/base/arithmeticOverflow.h and a gtest.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. No fix for this is in progress yet; I'm investigating the 03312_line_numbers extra query_log rows in Stateless tests (arm_binary, parallel) and will follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix: #122751

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch (clean; the diff is still exactly the two PR files) so CI runs again. The only red check on the previous head was the rare 03312_line_numbers flake in Stateless tests (arm_binary, parallel). It isn't related to this PR, and its fix #122751 is still open.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 1, 2026
rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Oct 1, 2026
…y_log

The query_log listing could print the test's own
`SYSTEM FLUSH LOGS query_log, text_log` rows (`QueryStart 3 10` and
`QueryFinish 3 10`). A statement's QueryStart row is logged after its
interpreter executes, and for SYSTEM FLUSH LOGS the flush is the
execution, so both rows of that statement are queued only after its own
flush completed. They become visible when another flush (a concurrent
test's SYSTEM FLUSH LOGS, or the periodic one) commits them before the
listing reads the table. The server log of the failing job shows exactly
that: a flush requested by another test during this test's slow
query_log insert ran 14 ms after query 3 returned and committed its two
rows into a new part, and the listing, which started 108 ms after query 3
returned, read that part.

The reference pins only the rows of queries 1 and 2, so restrict the
listing to `script_query_number IN (1, 2)`. The reference is unchanged.

Related: ClickHouse#120808

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merged via the queue into ClickHouse:master with commit 9842ce8 Oct 1, 2026
149 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
lazerg pushed a commit to lazerg/ClickHouse that referenced this pull request Nov 17, 2026
…arter of their rows

No existing query number or text changes: 2 queries (20 numbered entries) are disabled and 4 (20
entries) appended, as 26-45. The two `{type}` queries get `disabled="1"`, which stops all ten of
their expansions; the 16 sub-second ones (master's 0-4, 7-14, 17-19) are appended verbatim through
a new `{narrow_type}` substitution, the four over Int128 and UInt256 (master's 5, 6, 15, 16: 1.49-2.43 s
on MasterCI amd, 1.18-1.50 s on arm) through `{wide_type}` on numbers(500000) instead of 2000000.

Each of the four sorts 2M arrays of 32 16- or 32-byte elements on one thread through the typed fast
path of ClickHouse#109832; user time is linear in rows. The copies keep the same 65409-row blocks (8 instead of
31) and the same per-block work. Every run also pays a fixed fault-in of its block after perf.py's
jemalloc purge, as on MasterCI.

Measured with perf.py on the official MasterCI amd builds, 8 pinned cores, two repetitions on
different NUMA nodes (per-row gates with the L3 capped to 30 MiB, 20 runs per server):
- per-row user time copy / original 0.969-1.006; user-time sort share within 0.016;
- kept fraction of a per-row change 0.897-0.950 (fixed part 21-59 ms per run);
- ClickHouse#117346 (clang 23; MasterCI 0.878 amd / 0.913 arm on the UInt256 sort): original 0.911 / 0.916,
  copy 0.922 / 0.916; ClickHouse#120808 on the Int128 reverse sort: original 1.045 / 1.046, copy 1.051 / 1.044.

The Decimal128 query (entry 22) stays enabled: its copy kept under half of ClickHouse#120808's effect in one
of four pass measurements (0.42).

Projected copy medians 0.40-0.66 s amd, 0.31-0.41 s arm: about 21 s (amd) and 15 s (arm) less query
time per master perf job.

Related: ClickHouse#129258

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 comp-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. external Author is not a member of the ClickHouse organization 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.

Not a bug: ignore-overflow helpers rely on undefined signed overflow

4 participants