Skip to content

Fix several non-deterministic function results found by the functions stress test - #104710

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
Algunenano:fix-bit-rotate-determinism
May 12, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
Algunenano:fix-bit-rotate-determinism

Conversation

@Algunenano

@Algunenano Algunenano commented May 12, 2026 •

Copy link
Copy Markdown
Member

The functions stress test was catching a handful of functions returning different results for the same input depending on whether arguments arrived as columns or as constants. Each commit on the branch fixes one root cause and adds a stateless regression test that fails on the unfixed 26.3.9.8 binary:

  • bitRotateLeft / bitRotateRight: the canonical shift-pair form (a << b) | (a >> (bits - b)) was undefined for b == 0 or b >= bits. clang lowered the vector path to scalar rol r, cl (hardware-masked, well-defined) but the right-constant path to a SIMD pslld + psrld + por that disagreed at the boundary. Replaced with the defined-rotation form (a << (s & (bits-1))) | (a >> ((-s) & (bits-1))); LLVM JIT uses llvm.fshl / llvm.fshr.
  • length(FixedString) and concatWithSeparator with LowCardinality(Nullable): wrapInNullable(ColumnConst, null_map) was reading only null_map[0] and broadcasting it to every row. With a per-row null map and a constant-collapsed result, every row inherited row 0's null state. Fixed in the helper; affected any function with the same shape.
  • roundDown: NaN inputs walked the boundary list using comparisons that are all false for NaN, so the linear-search path's carry-over iterator and std::upper_bound's strict-weak-ordering contract both produced different results in scalar vs vector. NaN now propagates through unchanged.
  • rightUTF8(s, -k) on invalid UTF-8: the dynamic-length path reformulated negative length as getSliceFromRight(elemSize - k, elemSize - k) which mixed countCodePoints (skips lone continuation bytes) with skipCodePointsForward/Backward (treats them as 1-byte code points). The constant-length path used the consistent getSliceFromLeft(|k|). Routed the dynamic path through the same helpers per row.

The final commit re-enables broken_determinism enforcement in the functions stress test (src/Functions/tests/gtest_functions_stress.cpp) now that all known triggers are fixed.

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):

Fix several functions returning different results for the same input depending on whether arguments arrived as columns or constants: bitRotateLeft / bitRotateRight (boundary shift counts), length(FixedString) / concatWithSeparator with LowCardinality(Nullable) inputs, roundDown on NaN, and rightUTF8 on invalid UTF-8.

Version info

  • Merged into: 26.5.1.582

Algunenano and others added 6 commits May 12, 2026 15:02
`bitRotateLeft(a, b)` and `bitRotateRight(a, b)` used the canonical
shift-pair form `(a << b) | (a >> (bits - b))`, suppressed UBSan with
`NO_SANITIZE_UNDEFINED`. For `b >= bits` or `b == 0` both shifts hit
undefined behaviour in C++. In practice clang lowered:
  - the vector path with a column-driven shift count to scalar `rol r, cl`
    (hardware rotation, which masks the count and is well-defined);
  - the right-constant path to SIMD `pslld + psrld + por`;
  - and the constant/constant path to a compile-time fold of the UB form.

These three paths happened to agree for `b in [1, bits-1]` but diverged
at boundaries (e.g. `bitRotateLeft(toUInt8(0x12), toUInt8(255))` returned
`0` instead of `9` because the constant fold of `(0x12 << 255) | (0x12
>> 9)` collapses to `0` under UB rules, while a real `rolb` masks the
count to 0..7).

Use the canonical defined-rotation form
`(a << (s & (bits-1))) | (a >> ((-s) & (bits-1)))`. Both shifts are now
masked into `0..bits-1` so neither is UB regardless of `b`. Clang
recognises the pattern and emits `rol r, cl` for both vector and
constant paths, eliminating the divergence.

LLVM JIT path switched from the same UB-prone shift pair to the
`llvm.fshl` / `llvm.fshr` funnel-shift intrinsics, which are also
defined for every shift amount.

Caught by the functions stress test as `broken_determinism`.

Adds a stateless test (`04229_bit_rotate_determinism`) that asserts
`bitRotateLeft`/`bitRotateRight` give consistent results across const,
materialized, and round-trip paths at boundaries (`0`, `bits`,
`bits + 1`, and counts much larger than `bits`). On the unfixed
`26.3.9.8` official binary the test fails (`bitRotateLeft(toUInt8(0x12),
toUInt8(255)) != bitRotateLeft(toUInt8(0x12), toUInt8(7))`).

Performance on the actual clickhouse binary, sum over 100M rows
(best of 5):

  Query                                          Old    New
  bitRotateLeft(u64, u64 % 64)                  0.070s 0.057s  (-19%)
  bitRotateLeft(u32, u32 % 32)                  0.071s 0.067s   (-6%)
  bitRotateLeft(u32, 13)                        0.033s 0.043s  (+30%)
  bitRotateLeft(u64, 13)                        0.032s 0.039s  (+22%)

Constant-shift cases get slower because clang now picks scalar `rol`
over the OLD code's incidental SIMD lowering. Variable-shift cases get
faster because clang's recognition is tighter.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`wrapInNullable(src, null_map)` in `src/Functions/FunctionHelpers.cpp`
took a shortcut when `src` was a `ColumnConst`: it produced a single
`ColumnNullable` with one null bit, reusing `null_map[0]` for every
row. With a real per-row null map (e.g. some rows null, some not), the
result silently broadcast row 0's null state to all rows, dropping the
information for every other row.

The only function inside `src/Functions/` that reliably hits this path
today is `length(FixedString(N))`, which collapses the result to
`ColumnConst(N)` via `is_fixed_to_constant` and then defers null
handling to the default wrapper. Reproducer that returned the wrong
value:

  SELECT length(x) FROM (
      SELECT multiIf(number = 0, NULL,
                     number = 1, CAST('hello\0\0\0\0\0' AS Nullable(FixedString(10))),
                     NULL) AS x FROM numbers(4))

returned `NULL` for row 1 instead of `10`.

When the input null map is uniform (or absent) the constant-collapsed
output is still correct, so the shortcut is kept for that case. When
the null map is heterogeneous, expand the constant to a full column
and merge the inner null bit (if the constant wraps a Nullable) into
the per-row null map.

Caught by the functions stress test as `broken_determinism` on
`length`.

Adds `04230_length_nullable_fixed_string` which fails on the unfixed
26.3.9.8 binary and passes on this branch.

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

`concatWithSeparator(sep)` with only a separator argument collapses to
`ColumnConst('')`, then went through the default null wrapper. Before
the previous commit's fix to `wrapInNullable`, a `LowCardinality(Nullable(
FixedString))` separator with a per-row null map had row 0's null bit
broadcast to every row — so a non-null row got `NULL` and a null-const
input got `''`. The functions stress test caught the divergence as
`broken_determinism` ("NULL vs ''").

The underlying bug was fixed in the previous commit; this test pins
the behaviour. On the unfixed 26.3.9.8 binary the same test fails (row
1's not-null value comes out as `NULL`, and `materialize(NULL)` comes
out as `''`).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`roundDown(nan, [...])` returned different values in the scalar and
vector paths. Both paths walked the sorted boundaries using
comparisons that all evaluate to false for NaN:

  - the linear-search path (boundary list < 32 elements) carries the
    iterator `it` over from the previous iteration as a hint; for NaN
    both `*it < value` and `*it > value` are false so `it` stays where
    the last finite value left it. The result depends on prior rows.

  - the binary-search path calls `std::upper_bound`, whose
    strict-weak-ordering contract is violated by NaN. The returned
    position is implementation-defined.

Detect NaN at the top of each loop body (using the project's
`isNaN` helper which also covers `BFloat16`, gated by the
`is_floating_point` concept which includes it) and propagate the NaN
unchanged. Decimal containers can't hold NaN so the check compiles
away there.

Caught by the functions stress test as `broken_determinism`
("`roundDown(nan, [3, -4])` returns `3` scalar vs `-4` vector").

Adds `04232_round_down_nan_determinism`, which fails on the unfixed
26.3.9.8 binary and passes here. Covers both Float32 and Float64, and
exercises both the linear-search and binary-search code paths.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`rightUTF8(s, -k)` returned different results when the length argument
arrived as a column instead of a constant, on strings that contained
lone continuation bytes (invalid UTF-8).

The constant-length path used `getSliceFromLeft(|k|)` (unbounded) which
internally relies on a single algorithm — `skipCodePointsForward` — so
it stays self-consistent.

The dynamic-length path went through `sliceFromRightDynamicLength` →
`sliceDynamicOffsetBoundedImpl<true>`, which reformulated `right(s, -k)`
as `getSliceFromRight(elemSize - k, elemSize - k)`. That formulation
mixes two UTF-8 counting routines:

  - `elemSize = UTF8::countCodePoints(...)` skips lone continuation
    bytes (it counts bytes outside the 0x80..0xBF range).
  - `skipCodePointsForward/Backward` treat lone continuation bytes as
    1-byte code points via `UTF8::seqLength` (which returns 1 for them).

The mismatch silently dropped trailing bytes from the result. For
`'aaa' || char(0xA0) || 'bbb'` and `length = -1`:

  - const path:   `aa` || 0xA0 || `bbb`  (6 bytes, correct)
  - dynamic path: `aa` || 0xA0 || `bb`   (5 bytes, missing 'b')

Stop routing the right-direction dynamic length through the unified
bounded helper. Iterate per row in `executeForSource` and call the same
unbounded `getSliceFromLeft(|length|)` / `getSliceFromRight(length)`
helpers that the constant-length path uses. The positive-length and
zero-length cases keep their semantics; only the negative-length code
path changes (and only for invalid UTF-8 input, where the const and
dynamic paths used to disagree).

Caught by the functions stress test as `broken_determinism`. Adds
`04233_right_utf8_invalid_utf8_determinism` which fails on the unfixed
26.3.9.8 binary and passes here.

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

clickhouse-gh Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5192762]

Summary: ✅


AI Review

Summary

This PR fixes several column-vs-const determinism bugs in bitRotateLeft/bitRotateRight, wrapInNullable, roundDown, and rightUTF8, adds focused stateless regressions, and re-enables broken_determinism in the functions stress test. I found no unresolved correctness, safety, or PR-metadata issues in the current diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 12, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 88.10% (74/84) | lost baseline coverage: 1 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this May 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 12, 2026
Merged via the queue into ClickHouse:master with commit 53fa6a5 May 12, 2026
485 of 487 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 12, 2026
Ergus pushed a commit to Ergus/ClickHouse that referenced this pull request Jun 11, 2026
roundDown(value, boundaries) returned different results for the same input
depending on whether it was evaluated in a single-row or multi-row batch when
the boundaries array contained NaN. For example:

  SELECT roundDown(materialize(1::Int32), [3.25e-38, nan, 2.85e-38, nan]::Array(Float32));
  -- 3.25e-38

  SELECT roundDown(a, [3.25e-38, nan, 2.85e-38, nan]::Array(Float32))
  FROM system.one ARRAY JOIN [1, ...]::Array(Int32) AS a;
  -- nan for the same value

executeImplNumToNum sorts the boundaries with ::sort and then walks them. An
array containing NaN violates the strict-weak-ordering contract of ::sort, so
the finite elements end up in an unspecified order. The small-array linear
search reuses the previous row's iterator as a hint, so it can get stuck on a
NaN slot, and the result of a finite input then depends on the other rows in
the batch.

A NaN boundary has no position in the ordering (every comparison against it is
false), so it can never be selected as a round-down target. Drop NaN boundaries
before sorting, which restores the ordering invariant and makes both the
linear-search and binary-search paths deterministic. If every boundary is NaN
the result is NaN for every row, as before.

The existing NaN handling (PR ClickHouse#104710) only covered NaN in the input value, not
NaN in the boundaries array, which is the case fixed here.

Closes ClickHouse#104877

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

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

Development

Successfully merging this pull request may close these issues.

3 participants