Skip to content

Fix least/greatest with a NaN argument returning different results with and without JIT - #126022

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/least-greatest-nan-jit
Oct 21, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/least-greatest-nan-jit

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120728

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 least and greatest with two floating-point arguments returning a different result for a NaN argument depending on the argument order and on whether the expression was JIT-compiled, so the same query could change its result from its 4th execution at default settings. A NaN argument now loses against any number, as in the variadic form. Closes #120728.

Description

On 26.8.18.2 (also 26.3.42.3 and master), two-argument least/greatest over Float32/Float64 returns a different value for a NaN argument interpreted and JIT-compiled, so at default settings an unchanged query changes its answer from its 4th run: SELECT least(-x, nan) FROM values('x Float64', -1.0) run five times returns nan nan nan 1 1.

The interpreted apply is a < b ? a : b: a NaN on the right wins and a NaN on the left loses (least(1, nan) = nan, least(nan, 1) = 1). The compiled body is llvm.minnum, where a NaN always loses. greatest mirrors both with > and llvm.maxnum. The two paths also disagree for equal operands of different sign (-0. and 0.).

Both apply and the compiled body now compute (x < y || isNaN(y)) ? x : y (> for greatest) through candidateReplacesBest in LeastGreatestGeneric.h, which the variadic numeric fold also uses. A NaN loses against any number and the result is NaN only when both arguments are, as in the variadic and Nullable forms (tests 01246, 04509) and the min/max aggregates. Ties still differ: the binary form returns the right operand (least(0., -0.) stays -0, pinned by 01246), the variadic form the earlier argument. min2/max2 are separate, never compiled functions and are not changed.

Price, in a standalone AVX2 loop (-O3 -march=x86-64-v3, 1% NaN): one vminpd becomes a compare, an unordered compare, an or and a blend, 0.246 -> 0.263 ns/row for Float64 (+7%) and 0.089 -> 0.099 ns/row for Float32 (+12%) interpreted; the compiled loop changes by about 1%.

The new test runs both argument orders for Float32/Float64, Int32 promoted to Float64 and signed zeros with and without compilation, plus constant folding, BFloat16 and least_greatest_legacy_null_behavior. It fails on master, fails with only apply fixed, and passes 50/50 randomized runs.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.412-master (included in 26.11 and later)

Two-argument `least`/`greatest` over floats returned the NaN for a NaN on the
right in the interpreted `apply` (`a < b ? a : b`), but the number in the
compiled body (`llvm.minnum` / `llvm.maxnum`). The result of an unchanged query
therefore flipped once the expression was JIT-compiled (from its 4th execution
at default settings). The two bodies also disagreed for equal operands of
different sign.

Both bodies now compute `(x < y || isNaN(y)) ? x : y` (`>` for `greatest`): a
NaN loses against any number, as in the variadic `least`/`greatest` and the
`min`/`max` aggregates, and a tie still returns the right operand.

Closes ClickHouse#120728

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (3 nits, no blocker or major).

# Sev Finding Verdict Evidence / action
1 💡 Description implied the variadic form shares the tie rule; it keeps the earlier argument on a tie (LeastGreatestGeneric.h, takesPrecedence) AGREE description now says only the NaN rule is shared
2 💡 min2/max2 keep a < b ? a : b; they are not compilable, so they have no execution-mode flip AGREE one sentence in the description, no code change
3 💡 The least/greatest documentation does not state the NaN rule noted, not blocking none

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20261015-122700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. least(-x, nan), least(nan, -x), greatest(-x, nan), greatest(nan, -x) over values('x Float64', -1.0) gives nan 1 nan 1 with compile_expressions = 0 and 1 1 1 1 with min_count_to_compile_expression = 0; the same query run five times at default settings gives nan nan nan 1 1. Same on master, 26.8.18.2 and 26.3.42.3.
b Root cause explained? The interpreted apply is a bare < / >, so a NaN on the right wins and a NaN on the left loses. The compiled body is llvm.minnum / llvm.maxnum, where a NaN always loses (and the left operand wins a signed-zero tie). The JIT replaces the interpreted body after 3 executions, so the result flips.
c Fix matches root cause? Yes. apply and the compiled body now compute the same predicate, (x < y || isNaN(y)) ? x : y (> for greatest). No guard, no setting.
d Test intent preserved / new tests added? New 05401_least_greatest_nan_compiled with interpreted and compiled arms plus a check that the expressions compile. 01246, 04509, 05097 unchanged and green.
e Both directions demonstrated? Fails on master (interpreted NaN rows, compiled signed-zero row, constant, BFloat16, legacy NULL rows), passes with the fix. With only apply fixed it still fails on the compiled signed-zero row. 50/50 randomized runs pass.
f Fix is general across code paths? Both least and greatest, interpreted vector/constant loops, constant folding and the JIT body. The variadic and Nullable path already lets NaN lose; integer branches cannot see NaN.
g Fix generalizes across inputs (params/datatypes/wrappers)? Float32, Float64, Int32 promoted to Float64, BFloat16, Nullable with least_greatest_legacy_null_behavior = 1, constants, both argument orders, both NaN, infinities, signed zeros.
h Backward compatible? (maintainer-approved exception only) No setting or format change. Only results that already changed with the execution count are affected; compiled and interpreted now agree.
i Invariants and contracts preserved? Result type unchanged; values without NaN unchanged (a tie still returns the right operand); no state or concurrency involved.

Session id: cron:clickhouse-impl-slot-4:20261015-120100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Ergus @george-larionov, could you review this and add the can be tested label (I cannot add labels right now, so CI does not start without it)? Two-argument least/greatest on floats compared with a bare </> when interpreted but used llvm.minnum/llvm.maxnum when JIT-compiled, so a NaN argument gave a different result from the 4th run on; both paths now compute (x < y || isNaN(y)) ? x : y.

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [35098dd]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Cannot list the mutations left unfinished by the stress phase FAIL cidb IGNORED
Cannot count the mutations left unfinished by the stress phase FAIL cidb IGNORED
Cannot run the mutation entries left behind by the killed mutations (see undrained_mutation_errors.txt) FAIL cidb IGNORED
Cannot submit the mutation that has to survive the upgrade FAIL cidb IGNORED
Cannot list the row policies left by the stress phase FAIL cidb IGNORED
Segmentation fault (STID: 5726-4458) FAIL cidb IGNORED

AI Review

Summary

The PR makes two-argument least and greatest agree between interpreted and JIT execution for NaN and signed zeros, while sharing the numeric comparison rule with the variadic implementation. Reviewed the current diff, surrounding execution paths, regression tests, and all prior discussion. No actionable findings remain.

Missing context / blind spots
  • ⚠️ Full CI for 35098dd04ebe2cb46ccfea903e46377a35a95955 is still running. The new regression passed the current Fast test; it also passed five ARM binary runs on the original implementation commit. Completion of the remaining head CI will close this validation gap. No local build or tests were run.
Final Verdict

✅ Approve. No changes requested.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Oct 15, 2026
@Algunenano Algunenano self-assigned this Oct 15, 2026
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b23673a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05345_text_index_prewhere_read_step_order flaky, not from this PR (it only changes least/greatest): the known read_order_index_first 0 -> 1 diff in the ParallelReplicas lane, 84 of 84 reruns passed; it failed on 52 PRs and on master in the last 30 days #125892 (mine, open)
Mergeable Check, PR praktika rollups of the row above #125892 (mine, open)

CIDB has no other FAIL or ERROR row from the finished run on this head.

Session id: cron:our-pr-ci-monitor:20261015-170015

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

🤖 The fix looks right, and the branchless (x < y || isNaN(y)) ? x : y is a good choice. I checked CompareHelper<T>::less(x, y, 1) as an alternative: with clang at -O3 -march=x86-64-v3 its vectorized loop is about twice as many instructions, because it has to keep less(nan, nan) == false for sorting. So no need to switch to it. Three requests:

  1. Reduce the duplication. The "NaN loses" rule is now written three times in C++: LeastBaseImpl::apply, GreatestBaseImpl::apply, and takesPrecedence in LeastGreatestGeneric.h. Both least.cpp and greatest.cpp already include that header, so one small helper there could serve all three. For example, candidate < best || isNaN(best) (with > for greatest) as "the candidate replaces the current best". The variadic loop's extra !isNaN(incoming) check only changes which NaN is kept when both are NaN, so it can be dropped.

  2. Fix the claim about the variadic form. The description says the binary form now behaves "as in the variadic form". That holds for NaN, but not for ties:

    SELECT 1/least(materialize(-0.), materialize(0.))                     -- inf: binary returns the right operand
    SELECT 1/least(materialize(-0.), materialize(0.), materialize(0.))    -- -inf: variadic keeps the earlier argument
    

    The new test locks in "the right operand wins" for the binary form. Either make the binary form keep the left operand on ties, like the variadic one (the shared helper from point 1 gives you that for free), or reword the description and the code comments to say only NaN handling matches.

  3. Drop the query_log / CompiledFunctionExecute block in the test. It needs SYSTEM FLUSH LOGS plus a query_log scan, which is expensive for a stateless test. And it doesn't add much: before the fix, the JIT-on and JIT-off sections already give different output, so the reference file catches the regression by itself.

Comment thread src/Functions/least.cpp Outdated
const auto x = static_cast<Result>(a);
const auto y = static_cast<Result>(b);
/// NaN loses against any number, as in the variadic `least`.
return (x < y || isNaN(y)) ? x : y;

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.

🤖 This is the same rule as takesPrecedence in LeastGreatestGeneric.h, apart from tie handling. Could both use one helper? See the review body.

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.

Done in 4e195dc: one helper, candidateReplacesBest, now used by both apply and the variadic fold.

greatest(materialize(toNullable(1.)), materialize(toNullable(nan)))
SETTINGS least_greatest_legacy_null_behavior = 1, compile_expressions = 0;

-- The carriers are compiled whenever a compilable control is

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.

🤖 Suggest removing this block. The SYSTEM FLUSH LOGS and query_log lookup are costly, and the JIT on/off result comparison above already fails without the fix.

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.

Removed in 4e195dc.

`candidateReplacesBest` in `LeastGreatestGeneric.h` is now the one place that
says a NaN loses against any number. The two-argument `apply` of `least` and
`greatest` and the variadic numeric fold both use it.

The binary form passes its right operand as `best`, so its results are
unchanged, including ties: a tie still returns the right operand, and
`least(0., -0.)` stays `-0` as `01246_least_greatest_generic` expects. The
variadic fold no longer special-cases a NaN candidate, which only changes which
NaN is returned when every argument is NaN.

Drop the `query_log` check from the test: without the fix the JIT-on and JIT-off
sections already give different results.

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

Copy link
Copy Markdown
Collaborator Author

Thanks, all three are addressed in 4e195dc.

  1. candidateReplacesBest in LeastGreatestGeneric.h now holds the rule (candidate < best || isNaN(best), > for greatest). The variadic fold and both binary apply use it, and the !isNaN(incoming) check is gone.
  2. I took the reword option. Keeping the left operand on ties would change least(0., -0.) from -0 to 0: master returns -0 there on both the interpreted and the JIT path, and 01246_least_greatest_generic pins it. So the binary form passes its right operand as best, its results are the same as in the previous commit, and the description and the code comment now say that only NaN handling matches the variadic form. If you still prefer left-on-tie, it is a small change plus that one 01246 reference line.
  3. Removed the query_log block. The remaining rows still cover the JIT body: with only the compiled body reverted to llvm.minnum/llvm.maxnum, the test fails on the signed zero JIT on row.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4e195dc

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy, 3/4) / Build ClickHouse master build break, not from this PR (it does not touch the file): unit_tests_dbms does not compile, gtest_functions_stress.cpp:2367: error: value of type 'const ResolvedAddress' is not contextually convertible to 'bool'; no diagnostic in the files of this PR #126269 (external, merged)
Finish Workflow / new_tests_check.py both functional Bugfix validation jobs were dropped because of the build failure above #126269 (the owner of the first row)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the rows above #126269 (the owner of the first row)

The build failure dropped 89 dependent jobs, so no functional test has run on this head yet. #126269 merged at 14:32Z, after this run was built.

Session id: cron:our-pr-ci-monitor:20261016-143004

@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 35098dd04 with master 074719710 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 5ba211c4d; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: compile time of recompiled translation units.

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

6 object files changed (+280.97 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/least.cpp.o 8.10 MiB 8.24 MiB +141.62 KiB (+1.71%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/greatest.cpp.o 8.12 MiB 8.26 MiB +139.34 KiB (+1.67%)

719 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 ⚠️

8 translation units recompiled, 51 s compile time in total, 6 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Functions/greatest.cpp: 23.6 s
  • src/Functions/least.cpp: 23.3 s

Job report

@Algunenano

Copy link
Copy Markdown
Member

@groeneai Please verify the crash in the upgrade check

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 35098dd

I checked the Upgrade check crash, and this PR did not cause it. The server that crashed is the previous release 26.9.22.3 (official build, git hash 3aba10ed64fa) during the stress phase, running that release's own test 04768_parallel_replicas_right_join_null_conjunct with grace_hash first in the randomized join_algorithm (fatal.log). It is the GraceHashJoin / TemporaryBlockStreamHolder null-column crash fixed by #126204. Its 26.9 backport #126911 is in 26.9.23.15, released 2026-10-20 17:23Z, after this job downloaded 26.9.22.3. Upgrade check runs since 2026-10-17 hit this crash in 35 of 970 runs before that release and in 0 of 237 after it. A re-run of this job should pass; I can't trigger one myself.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Segmentation fault (STID: 5726-4458) crash in the previous release 26.9.22.3 during the stress phase, not in this PR's build #126204 (mine, merged), 26.9 backport #126911 (merged, in 26.9.23.15)
Upgrade check (amd_release) / Cannot list the mutations left unfinished by the stress phase the server was already down after the crash (Connection refused) #126204 (the owner of the first row)
Upgrade check (amd_release) / Cannot count the mutations left unfinished by the stress phase the server was already down after the crash (Connection refused) #126204 (the owner of the first row)
Upgrade check (amd_release) / Cannot run the mutation entries left behind by the killed mutations (see undrained_mutation_errors.txt) the server was already down after the crash (Connection refused) #126204 (the owner of the first row)
Upgrade check (amd_release) / Cannot submit the mutation that has to survive the upgrade the server was already down after the crash (Connection refused) #126204 (the owner of the first row)
Upgrade check (amd_release) / Cannot list the row policies left by the stress phase the server was already down after the crash (Connection refused) #126204 (the owner of the first row)
Upgrade check (amd_release), Mergeable Check, PR job status and praktika rollups of the rows above #126204 (the owner of the first row)

Session id: cron:clickhouse-premium-slot-25:20261021-110700

@Algunenano

Copy link
Copy Markdown
Member

Perfect. If upgrade check is on the old release and the fix is already backported everything is fine

@Algunenano
Algunenano enabled auto-merge October 21, 2026 11:16
@Algunenano
Algunenano added this pull request to the merge queue Oct 21, 2026
Merged via the queue into ClickHouse:master with commit 9c39d7d Oct 21, 2026
177 of 179 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 Oct 21, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #126022 to 26.10: Fix `least`/`greatest` with a NaN argument returning different results with and without JIT
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… returning different results with and without JIT
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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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-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 v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

least/greatest NaN: interpreted keeps it, JIT drops it - flips on 4th run

5 participants