Skip to content

Do not JIT-compile __bitSwapLastTwo for argument types it rejects - #117613

Merged
Manerone merged 3 commits into
ClickHouse:masterfrom
groeneai:jit-bit-swap-last-two-argument-type
Oct 1, 2026
Merged

Manerone merged 3 commits into
ClickHouse:masterfrom
groeneai:jit-bit-swap-last-two-argument-type

Conversation

@groeneai

@groeneai groeneai commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117590 (comment)
Related: #117442

Changelog category (leave one):

  • Improvement

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

The internal function __bitSwapLastTwo now raises the same BAD_ARGUMENTS error for unsupported argument types when the expression is JIT-compiled as when it is interpreted.

Description

__bitSwapLastTwo accepts only UInt8. It is internal (__-prefixed) but callable from SQL. When
the expression was JIT-compiled it answered for other argument types instead, so the same query
returned a value or raised depending only on whether it got compiled:

CREATE TABLE t (c0 UInt8) ENGINE = Memory;
INSERT INTO t VALUES (230), (250);

SELECT __bitSwapLastTwo(toFloat64(c0)) FROM t
    SETTINGS compile_expressions = 1, min_count_to_compile_expression = 0;
1
1

SELECT __bitSwapLastTwo(toFloat64(c0)) FROM t SETTINGS compile_expressions = 0;
Code: 36. DB::Exception: It's a bug! Only UInt8 type is supported by __bitSwapLastTwo. (BAD_ARGUMENTS)

Cause: BitSwapLastTwoImpl<A>::ResultType is UInt8 for every A, and
FunctionUnaryArithmetic::compileImpl casts the argument to the result type before calling
Op::compile. A Float64 argument was lowered with fptoui double to i8 and the swap ran on the
narrowed byte, while apply throws BAD_ARGUMENTS for any A other than UInt8.

compilable was true for every argument type; it is now std::is_same_v<A, ResultType>, so the
compiled domain equals the domain apply accepts and everything else falls through to the
interpreter, as it already did. UInt8 keeps its JIT coverage; wider and big integers lose the same
divergence. This follows c441505a8ffa8af ("Cover all input types in JIT intExp2"), the same
change to the same member, and the sibling __bitWrapperFunc (same UInt8 ResultType, same
throwing apply) is already compilable = false.

bitNot reaches the same lowering for floats and is deliberately not changed: its apply never
throws, so there is no defined interpreted answer to contradict, and #117590 discloses it.

The test rejects a float and an integral argument, since a gate excluding only floats would still
compile the latter; it passes with the change and fails without it. The isIntegerTy guard in
compile is removed, as the cast to the result type already made it unreachable.


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

Version info

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

`__bitSwapLastTwo` accepts only `UInt8`, but the compiled path answered for
any argument type, so the same query returned a value or raised
`BAD_ARGUMENTS` depending only on whether the expression got JIT-compiled:

    CREATE TABLE t (c0 UInt8) ENGINE = Memory;
    INSERT INTO t VALUES (230), (250);

    SELECT __bitSwapLastTwo(toFloat64(c0)) FROM t
        SETTINGS compile_expressions = 1, min_count_to_compile_expression = 0;
    -- returned 1, 1
    SELECT __bitSwapLastTwo(toFloat64(c0)) FROM t
        SETTINGS compile_expressions = 0;
    -- Code: 36 BAD_ARGUMENTS

`BitSwapLastTwoImpl<A>::ResultType` is `UInt8` for every `A`, and
`FunctionUnaryArithmetic::compileImpl` casts the argument to the result type
before calling `Op::compile`, so a `Float64` argument was lowered with
`fptoui double to i8` and the swap ran on the narrowed byte. The op is not in
the cast skip list, and `compile`'s own `isIntegerTy` guard cannot fire
because the cast has already made the value an integer. The interpreter never
gets that far: `apply` throws for any `A` other than `UInt8`.

Gate `compilable` on the domain `apply` accepts. `Op<T0>::compilable` is
consulted by both `isCompilableImpl` and `compileImpl`, and `T0` is the type
`apply` receives, so the compiled domain now equals the non-throwing
interpreted domain. This follows c441505 ("Cover all input types in
JIT intExp2"), which narrowed the same member from `true` to a type predicate
for the same reason. `UInt8` keeps its JIT coverage; wider and big integers
lose the same divergence.

`bitNot` reaches the same lowering for float arguments and is left alone: its
`apply` never throws, so there is no defined interpreted answer for the
compiled path to contradict. The only in-tree caller, `MergeTreeIndexSet`,
builds its `ExpressionActions` with the default `ExpressionActionsSettings`
(`can_compile_expressions = false`) and passes a `UInt8` `BoolMask`, so the
skip-index path is unaffected either way.

Related: ClickHouse#117590 (comment)
Related: ClickHouse#117442

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 2, 2026
@groeneai

groeneai commented Sep 2, 2026

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;
bounded: 1 full pass + 1 fix round + 1 delta recheck).

No findings. Coverage: the changed implementation and test, the generic FunctionUnaryArithmetic
JIT dispatcher, all callers, the wrapper paths and the sibling mask functions, plus local probes
confirming that the unsupported argument types are now rejected and that UInt8 is still compiled.

A preceding independent pass enumerated the invariant carriers on its own before reading the fix
plan and reached the same conclusion: of the 14 FunctionUnaryArithmetic instantiations, the five
that remain unconditionally compilable have no throw in apply, and the binary counterpart
already applies the same rule (DivisionUtils.h, "don't know how to throw from LLVM IR"), so this
was the last op whose compiled path could answer in a domain the interpreted path rejects.

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-11:20260902-031200

@clickhouse-gh clickhouse-gh Bot closed this Sep 2, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 2, 2026
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT __bitSwapLastTwo(toFloat64(c0)) FROM t SETTINGS compile_expressions = 1, min_count_to_compile_expression = 0 returns 1, 1 and exits 0 on the base binary, every time; compile_expressions = 0 raises BAD_ARGUMENTS. CompileFunction: 1 on the compiled arm confirms the expression really was JIT-compiled, so the probe is not vacuous.
b Root cause explained? Yes. BitSwapLastTwoImpl<A>::ResultType is UInt8 for every A, and FunctionUnaryArithmetic::compileImpl casts the argument to the result type before Op::compile (__bitSwapLastTwo is not in the skip list, which is exactly AbsImpl/BitCountImpl/IntExp2Impl/SignImpl). A Float64 argument is lowered fptoui double to i8 and the swap runs on the narrowed byte, while apply throws BAD_ARGUMENTS for any A != UInt8.
c Fix matches root cause? Yes. compilable is the per-argument-type gate the framework provides for this, consulted by both isCompilableImpl and compileImpl, and T0 is exactly the type apply receives. Setting it to std::is_same_v<A, ResultType> makes the compiled domain equal the non-throwing interpreted domain. Not a widened bound, not a blanket tag, not a defensive check masking something upstream.
d Test intent preserved / new tests added? Yes. Nothing removed or weakened; new stateless test 05056_jit_bit_swap_last_two_argument_type. It asserts the rejected type raises on both arms, the accepted type answers identically on both, and the accepted type is still compiled (its CompiledFunctionExecute > 0 flag compared against a control op rather than a literal, so the row also holds in a build with no embedded compiler). No -- Tags: line is needed for the same reason.
e Both directions demonstrated? Yes. Base: 1, 1 (rc 0, CompileFunction: 1). Fix: Code: 36 BAD_ARGUMENTS (rc 36, CompileFunction: 0). The compile_expressions = 0 column is byte-identical on both binaries, so the interpreted path is untouched. The new test passes on the fix and fails on pristine base with The query succeeded but the server error '36' was expected, which is what Bugfix validation checks.
f Fix is general across code paths? Yes. All 14 FunctionUnaryArithmetic instantiations enumerated and measured: after this change every op whose apply can throw is either compilable = false (7 ops) or gated by a type predicate (intExp2, and now this one), and the 5 remaining unconditional true ops (abs, bitCount, bitNot, negate, sign) have zero throws in apply. __bitSwapLastTwo was the only op whose compiled path could answer in a domain the interpreted path rejects, so no change to the shared driver is warranted. bitNot reaches the same lowering but is not a carrier: its apply never throws, so there is no defined interpreted answer to contradict.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured on both arms. Divergence removed for Float64, Float32, Nullable(Float64), UInt16, Int8, UInt128 (base returned a value, fix raises). Unchanged for UInt8, Nullable(UInt8), LowCardinality(UInt8), Bool. Date, Decimal64 and String are rejected during analysis on both arms. The gate is on T0 = DataType::FieldType, i.e. the type apply receives, so one predicate covers the wrapper matrix structurally rather than by enumeration.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default moves, so no SettingsChangesHistory.cpp entry; no serialization, format or ABI change. The only behaviour change is that an argument type the function documents as unsupported now raises the same error it already raised when interpreted, instead of returning a fabricated value. That cannot have been depended on: which of the two a user got depended only on whether the expression happened to be JIT-compiled.
i Invariants and contracts preserved? Yes. compilable is a compile-time constexpr bool read only by the two #if USE_EMBEDDED_COMPILER members of FunctionUnaryArithmetic; a false result routes the node to the interpreter, which is the framework's existing fallthrough (7 other ops rely on it). No lifetime, resource, concurrency, error-path or block-structure surface is touched, and no durability or crash-restart path is involved. The only in-tree caller, MergeTreeIndexSet, never JIT-compiles (default can_compile_expressions = false) and passes a UInt8 BoolMask, so the skip-index path is unaffected in either direction.

Additional validation: 50/50 randomised runs of the new test (--test-runs 50 --jobs 8) all pass, so it is self-parallel-safe. Regression sweep run on both binaries and compared as a set: the JIT family (17 tests, including 03595_funcs_on_zero, the only in-tree test calling __bitSwapLastTwo) and the set skip-index family (22 tests) are identical apart from the new test, plus four tests that fail on both arms with the same Code: 701 ... Requested cluster ... not found signature from the minimal local repro config. various_checks.sh and check_cpp.sh report no findings, verified live on the new file with a negative control.

Session id: cron:clickhouse-impl-slot-6:20260902-000200

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [512735e]

Summary: ✅


AI Review

Summary

This PR narrows __bitSwapLastTwo JIT compilation to the same UInt8 domain that the interpreted apply path already accepts, removes the now-unreachable JIT-side type guard, and adds a stateless regression test that covers both a floating-point and an integral rejected-type carrier while still checking that the accepted UInt8 shape keeps JIT coverage. I did not find any remaining correctness or test-coverage issues in the current revision that warrant a new review comment.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 512735e.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Ergus @rschu1ze, could you review this? __bitSwapLastTwo declared itself JIT-compilable for every argument type, but the shared unary-arithmetic compile path casts the argument to the op's fixed UInt8 result type, so a Float64 argument was narrowed with fptoui and answered a value where the interpreter raises BAD_ARGUMENTS. The fix gates compilable on std::is_same_v<A, ResultType>, the same narrowing c441505a8ffa8af did for intExp2.

@zlareb1

This comment was marked as low quality.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 512735e3b50f5a2143792cf6a7a5d78fba8e73b3 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

You are right, and my adjudication note is wrong. DivisionUtils.h gates the division family only (intDiv, modulo, moduloLegacy, positiveModulo), so the clause "the binary counterpart already applies the same rule ... this was the last op whose compiled path could answer in a domain the interpreted path rejects" is retracted. The shift/rotate quartet keeps compilable = true with an unguarded compile body, so a binary carrier is open and merging this PR does not close the class.

I reproduced all three legs of #117614 on 26.9.1.1, compile_expressions 1 vs 0 at min_count_to_compile_expression = 0:

  • 128-bit count: bitShiftLeft(-toInt64(number), toInt128(1)) over numbers(2) answers 0 and -2 compiled against NOT_IMPLEMENTED interpreted; bitRotateLeft in the same shape answers 0 and -1.
  • Negative count: bitShiftLeft and bitShiftRight answer 0 against ARGUMENT_OUT_OF_BOUND.
  • Oversized-for-A count: your mixed-width shape reproduces exactly, 65024 against 0 and -1 against 0, with your in-range control agreeing at 2040 on both paths.

Two boundary details for whoever writes the fix. The rotate pair has no negative-count throw: apply masks the count to 0..bits-1 and fshl/fshr mask it too, so bitRotateLeft(x, -1) agrees on both paths, which leaves the negative-count leg to the shift pair only. And a 256-bit count raises on both paths because those widths are not JIT-native, so the reachable type gap is the 128-bit ones.

Nothing changes in this PR.

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - be61f8a

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
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) Failures: 1/12. The job's log scanner flags an error a test asserts on purpose: the referenced file is 4 lines and all 4 are Cluster: Code: 198. DB::NetException: Not found address of host: <250-byte host> (DNS_ERROR), with 0 lines of any other error. Those are 04725_distributed_async_insert_long_directory_name's deliberately unresolvable Remote hosts being resolved by the restarted server, not a compatibility break and not this diff #117284 (mine, open)
Stress test (amd_debug) / Logical error: Not-ready Set is passed as the second argument for function 'globalIn' (STID 0250-4e52) pre-existing trunk defect on the object-storage _path / _file prefilter, not reachable from this diff: the abort runs ReadFromObjectStorageStep::createIterator into StorageObjectStorageSource::createFileIterator, VirtualColumnUtils::getFilterByPathAndFileIndexes and FunctionIn::executeImpl (src/Functions/in.cpp:128), and carries no FutureSetFromSubquery frame. 759 rows across 499 pull requests and 47 true-master trees in 30 days #112968 (external, open)

Note on why two rows: this head got two concurrent PR workflow runs (33588982190, 33588990250),
each of 170 jobs, and they failed different jobs. The shared report is last-writer-wins, so the check
list shows only the Upgrade check red; the Stress test red is real and is taken from CIDB at this
commit.

Session id: cron:our-pr-ci-monitor:20260902-083000

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

IIUC the fix closes the JIT leg, not the class. The type restriction is in apply instead of getReturnTypeImpl. Is this intended??


-- `__bitSwapLastTwo` accepts only `UInt8`. `toFloat64` is the compilable child that makes the
-- shape compilable at all: a lone `__bitSwapLastTwo(c0)` is never compiled.
SELECT __bitSwapLastTwo(toFloat64(c0)) FROM t_bit_swap_last_two

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 rejected-type arm uses only a float, so the test does not pin the gate

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.

Agreed. Measured on master (26.9.1.1): SELECT __bitSwapLastTwo(bitNot(toUInt16(number))) FROM numbers(2) returns 3 and 1 with compile_expressions = 1, min_count_to_compile_expression = 0, and raises BAD_ARGUMENTS with compile_expressions = 0. So an integral argument is a live case here, and a weaker gate such as !std::is_floating_point_v<A> would still pass this test as written.

I will add that arm. I am holding it for a single push together with the getReturnTypeImpl question in your review, since the answer there decides the expected error code.

Comment thread src/Functions/bitSwapLastTwo.cpp Resolved
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

Yes, intended, and you are right that the gate closes the JIT leg only.

The restriction stays in apply because that is the in-tree answer for this shape. __bitWrapperFunc has the same UInt8 ResultType, the same throwing apply and the same "Should be a logical error, but this function is callable from SQL" comment, and it is handled with compilable = false. intExp2 uses the type-predicate form of the same idiom (compilable = is_integer<A> && !is_big_int_v<A>, "we can't throw from JIT-compiled code"). So this PR removes the divergence and leaves the interpreted contract untouched.

Restricting the type in getReturnTypeImpl does close the class, and I will push that instead if you prefer it. It changes the interpreted contract, which is why I am asking rather than deciding. What it would change, measured on master (26.9.1.1):

  • a numeric non-UInt8 argument would move from BAD_ARGUMENTS at execution to ILLEGAL_TYPE_OF_ARGUMENT at analysis. That is the code String and Enum8 already get from this function, so it makes the function more consistent, not less.
  • queries that never reach apply today would start failing: SELECT __bitSwapLastTwo(toFloat64(number)) FROM numbers(0) returns an empty result on master.
  • the internal caller is unaffected: NOT c over a UInt64 or a Float64 indexed column works on master, which it could not if the set index NOT translation passed anything but UInt8 to this function.

One scope note if you want that version: __bitWrapperFunc carries the identical comment, so it should get the same treatment in the same PR and the diff becomes both functions.

Your call. If you have no preference I will keep the gate, drop the dead LOGICAL_ERROR check and add the integral rejected-type arm, in one push.

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 4, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

One correction before I push, because I gave you a wrong cost for the option you asked about.

I said restricting the type in getReturnTypeImpl would make the diff both functions. That is not
right. FunctionBitSwapLastTwo already overrides getReturnTypeForDefaultImplementationForDynamic,
so it is already the function-level customization point and the override lands in that one class.
__bitWrapperFunc does not have to change.

So your option is smaller than I described, and it is the more complete one. The JIT gate does not
close the analysis-time hole: SELECT __bitSwapLastTwo(toFloat64(number)) FROM numbers(0) still
returns an empty result today instead of rejecting the argument type.

What it would still change for users: a numeric non-UInt8 argument moves from BAD_ARGUMENTS at
execution to ILLEGAL_TYPE_OF_ARGUMENT at analysis, and zero-row queries start failing. The accepted
domain would have to keep UInt8, Bool, Nullable(UInt8) and LowCardinality(UInt8), which all
work today.

I would rather you choose than guess, because it decides the error code the new test arm pins:

  • keep the JIT gate: I push it as it stands, drop the dead LOGICAL_ERROR check, and add the integral
    rejected-type arm expecting BAD_ARGUMENTS;
  • move the restriction: I push the getReturnTypeImpl override instead, and the arm expects
    ILLEGAL_TYPE_OF_ARGUMENT, with an empty-input case.

@PedroTadim

Copy link
Copy Markdown
Member

cc @Manerone

@Manerone Manerone self-assigned this Sep 8, 2026

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

I have a question here. For cases where compilable=false means to take a path that as not compiled is intended to be very slow. In that case the user could face some performance impact with no clear information. DOes it makes sense to log or inform the user somehow in that case?

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Good question. For this PR the scope is narrow: the only argument types that stop being compiled are the ones the interpreter rejects. apply accepts exactly UInt8 (bitSwapLastTwo.cpp:27-30: every other A throws BAD_ARGUMENTS) and the new predicate is that same condition, so any query that evaluates the function successfully keeps the compiled path. UInt8, Bool, Nullable(UInt8) and LowCardinality(UInt8) are unchanged.

On the general point, compilable = false does not select a special slow path. It means the node is not fused into a generated function and runs through the ordinary vectorized implementation, which is the common case rather than the exception:

  • a node is only fused if it has at least one compilable child (ExpressionJIT.cpp:607), so a single function over a column is never compiled. Measured on a master build at compile_expressions = 1, min_count_to_compile_expression = 0, reading system.query_log: SELECT c0 + 1 FROM t gives CompileFunction 0, CompiledFunctionExecute 0, while SELECT (c0 + 1) * 2 - 3 FROM t gives 1 and 1;
  • compile() also declines until it has seen the same expression min_count_to_compile_expression times (ExpressionJIT.cpp:309, default 3), so the first executions of every query are uncompiled by design.

That is why I would not log it per expression: it would fire on almost every query, and the per-query answer is already retrievable from ProfileEvents['CompileFunction'], ProfileEvents['CompiledFunctionExecute'] and ProfileEvents['CompileExpressionsMicroseconds'] in system.query_log, which is exactly the measurement above. Successful compilation is additionally traced (ExpressionJIT.cpp:319); only the declined case has no line.

A useful "declined compilation" report would have to live in ActionsDAG::compileFunctions (ExpressionJIT.cpp:497-651), the only place that knows which maximal subtrees were rejected and why; a function impl cannot see it. That is a JIT-wide change, so I am not folding it into this bugfix. If you want it, say so explicitly and I will treat it separately.

Still open from my previous comment: keep the JIT gate, or move the type restriction to getReturnTypeImpl? That choice decides the error code the new test arm pins, so I am holding the push until you answer.

Comment on lines +34 to +43
WITH shapes AS
(
SELECT log_comment, argMax(ProfileEvents['CompiledFunctionExecute'] > 0, event_time_microseconds) AS compiled
FROM system.query_log
WHERE current_database = currentDatabase() AND type = 'QueryFinish'
AND log_comment IN ('05056_uint8', '05056_control')
GROUP BY log_comment
)
SELECT (SELECT compiled FROM shapes WHERE log_comment = '05056_uint8')
= (SELECT compiled FROM shapes WHERE log_comment = '05056_control');

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.

The "UInt8 still compiles" assertion at tests/queries/0_stateless/05056_jit_bit_swap_last_two_argument_type.sql:35-45 can pass vacuously.

Both sides of the comparison are scalar subqueries over shapes. If a query_log row is missing, the scalar subquery yields the UInt8 default 0, so the assertion becomes 0 = 0 → 1
and the reference still matches. This is the only assertion that the kept JIT coverage is real, so it should fail loudly rather than silently degrade to asserting nothing.

A presence check keeps it honest:

SELECT count() = 2 FROM shapes;

(plus the corresponding 1 in the reference), or fold it into the existing assertion with ... AND (SELECT count() FROM shapes) = 2.

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.

The premise does not hold on master: an empty scalar subquery evaluates to NULL, not to the type's default. Both analyzers wrap the type in Nullable and insert a Null literal: src/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp:315-343 and src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp:225-242.

So a missing query_log row makes the statement print \N, which does not match the reference 1. Measured on a master debug build (26.9.1.1, USE_EMBEDDED_COMPILER=ON) by running exactly that statement with only the log_comment values changed:

both rows present   ->  1     (matches the reference)
one row missing     ->  \N    (fails)
both rows missing   ->  \N    (fails)

Identical with enable_analyzer = 0. So count() = 2 would restate what NULL propagation already enforces, and I would rather not add a line for it.

The degenerate case that is real is the other one: both rows present with compiled = 0 on a build without the embedded compiler, where 0 = 0 passes and asserts nothing. That one is deliberate (the comment above the statement says why), and it can be closed:

SELECT (SELECT compiled FROM shapes WHERE log_comment = '05056_uint8')
     = (SELECT compiled FROM shapes WHERE log_comment = '05056_control'),
       (SELECT compiled FROM shapes WHERE log_comment = '05056_control')
     = ((SELECT value FROM system.build_options WHERE name = 'USE_EMBEDDED_COMPILER') = 'ON');

On that build it prints 1 1, and \N \N with the rows absent. It turns "the control compiled" into a hard requirement, so I would verify it against this branch's own build before pushing. Tell me which you want (that, or your count() = 2 after all) and it goes into the next push.

That push is still held on the open design question in the conversation tab, keep the JIT gate or move the type restriction to getReturnTypeImpl, because the answer decides the error code the new test arm pins.

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.

SELECT (SELECT compiled FROM shapes WHERE log_comment = '05056_uint8')
     = (SELECT compiled FROM shapes WHERE log_comment = '05056_control'),
       (SELECT compiled FROM shapes WHERE log_comment = '05056_control')
     = ((SELECT value FROM system.build_options WHERE name = 'USE_EMBEDDED_COMPILER') = 'ON');

go with this one

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.

Applied exactly as you quoted it, with the comment above the statement reworded to say what the second column requires.

Verified on this branch's own build (26.9.1.1, USE_EMBEDDED_COMPILER = ON), which is what I said I would do before pushing:

as shipped, both queries compiled                    1 1     passes
both logged queries forced onto the uncompiled path  1 0     fails
both query_log rows absent                           \N \N   fails

The middle row is the case the second column exists for: with compiled = 0 on both shapes the single-column form printed 1 and passed, while the new form makes clickhouse-test report result differs with reference.

On the lanes with no embedded compiler, which is the one risk of tying the assertion to the build: USE_EMBEDDED_COMPILER is an unconditional row in StorageSystemBuildOptions.cpp.in, and configure_file degrades an unset variable to the empty string rather than dropping the row. fasttest (ENABLE_LIBRARIES=0) therefore reports '' and MSan reports OFF, both of which give 0 = 0 in the second column, so the arm stays green there and needs no no-fasttest or no-msan tag.

The commit is local for now. The push is still held on the open design question in the conversation tab, keep the JIT gate or move the type restriction to getReturnTypeImpl, because that answer decides the error code the rejected-type arm pins; this change goes out with it.

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.

keep the JIT gate

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.

getReturnTypeImpl seems to be the better approach then, as EXPLAIN header = 1 SELECT __bitSwapLastTwo(toFloat64(c0)) FROM t is not really valid. Cant we leave this code as it is, and have getReturnTypeImpl in a separated PR?

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.

Yes, that is the split I would pick too.

That was Ergus's question, so I have asked him for a re-review rather than close it on his behalf. If he has no preference I take the default I offered him on 2 September: keep the gate as it stands, drop the isIntegerTy check in compile that the gate makes unreachable, and extend the test's rejected-type arm past a single float so it pins the gate.

Your two-column change is committed here and goes out in the same push.

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.

Ergus passed the PR to me, you can follow what I say

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: I kept the gate as it is, dropped the isIntegerTy check in compile that it makes unreachable, and added an integral argument to the rejected-type arm, which on master answers when compiled and raises when interpreted (512735e). Your two-column assertion is in f750111.

I will open the getReturnTypeImpl change as a separate PR and link it here. I also moved the changelog category from Bug Fix to Improvement, since __bitSwapLastTwo is an internal function.

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.

I opened the getReturnTypeImpl change as a separate PR: #122748.

The "`UInt8` still compiles" assertion compared the two shapes only, so it
also passed when both shapes reported `compiled = 0` on a build that does
have the embedded compiler. The arm then asserted nothing about JIT, which
is the one thing it exists to assert. Requiring the control's flag to agree
with `system.build_options` leaves both-zero passing only on a build that
really lacks the compiler.

Measured on this branch (26.9.1.1, `USE_EMBEDDED_COMPILER = ON`, buildId
db2f48c8a8c56fc63d3cc635356d98d1e3c8fb28): the test passes with `1 1`, and
with both logged queries forced onto the uncompiled path it fails with
`1 0` where the previous single-column form printed `1` and passed.

Requested by ClickHouse#117613 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai
groeneai requested a review from Ergus September 21, 2026 10:17
The `isIntegerTy` guard in `BitSwapLastTwoImpl::compile` cannot fire, and
could not fire before this PR either: `BitSwapLastTwoImpl` is not in the cast
skip list in `FunctionUnaryArithmetic::compileImpl`, so the argument goes
through `nativeCast(b, arguments[0], result_type)` first, and `result_type` is
`UInt8` for every argument type, so the value reaching `compile` is always
`i8`. Removing it loses no signal. `intExp2` keeps its copy of the check: it
is in that skip list, so it does see the raw argument.

The test only rejected a float, so a weaker gate such as
`!std::is_floating_point_v<A>` would have passed it. An integral argument
reaches the same rejection through a different lowering (`trunc` rather than
`fptoui`), so it gets its own arm: on unfixed code
`__bitSwapLastTwo(bitNot(toUInt16(c0)))` answers `2`, `2` when compiled and
raises `BAD_ARGUMENTS` when interpreted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Fix JIT-compiled __bitSwapLastTwo answering for argument types it rejects Do not JIT-compile __bitSwapLastTwo for argument types it rejects Sep 28, 2026
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 28, 2026
@Manerone
Manerone added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit d96270d Oct 1, 2026
294 of 295 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
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... groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-improvement Pull request with some product improvements 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.

6 participants