Repository navigation
Do not JIT-compile __bitSwapLastTwo for argument types it rejects - #117613
Conversation
`__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]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 0 findings; No findings. Coverage: the changed implementation and test, the generic A preceding independent pass enumerated the invariant carriers on its own before reading the fix Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-11:20260902-031200 |
Pre-PR validation gate (click to expand)
Additional validation: 50/50 randomised runs of the new test ( Session id: cron:clickhouse-impl-slot-6:20260902-000200 |
|
Workflow [PR], commit [512735e] Summary: ✅
AI ReviewSummaryThis PR narrows Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit 512735e.
Changed lines: Changed C/C++ lines covered: 3/3 (100.00%) · Uncovered code |
|
cc @Ergus @rschu1ze, could you review this? |
This comment was marked as low quality.
This comment was marked as low quality.
Build profile diff (arm_release)Commit See the job log for details. |
|
You are right, and my adjudication note is wrong. I reproduced all three legs of #117614 on 26.9.1.1,
Two boundary details for whoever writes the fix. The rotate pair has no negative-count throw: Nothing changes in this PR. |
CI finish ledger - be61f8aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Note on why two rows: this head got two concurrent Session id: cron:our-pr-ci-monitor:20260902-083000 |
Ergus
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
The rejected-type arm uses only a float, so the test does not pin the gate
There was a problem hiding this comment.
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.
|
Yes, intended, and you are right that the gate closes the JIT leg only. The restriction stays in Restricting the type in
One scope note if you want that version: Your call. If you have no preference I will keep the gate, drop the dead |
|
One correction before I push, because I gave you a wrong cost for the option you asked about. I said restricting the type in So your option is smaller than I described, and it is the more complete one. The JIT gate does not What it would still change for users: a numeric non- I would rather you choose than guess, because it decides the error code the new test arm pins:
|
|
cc @Manerone |
Ergus
left a comment
There was a problem hiding this comment.
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?
|
Good question. For this PR the scope is narrow: the only argument types that stop being compiled are the ones the interpreter rejects. On the general point,
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 A useful "declined compilation" report would have to live in Still open from my previous comment: keep the JIT gate, or move the type restriction to |
| 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'); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Ergus passed the PR to me, you can follow what I say
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
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]>
__bitSwapLastTwo answering for argument types it rejects__bitSwapLastTwo for argument types it rejects
d96270d
Related: #117590 (comment)
Related: #117442
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The internal function
__bitSwapLastTwonow raises the sameBAD_ARGUMENTSerror for unsupported argument types when the expression is JIT-compiled as when it is interpreted.Description
__bitSwapLastTwoaccepts onlyUInt8. It is internal (__-prefixed) but callable from SQL. Whenthe 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:
Cause:
BitSwapLastTwoImpl<A>::ResultTypeisUInt8for everyA, andFunctionUnaryArithmetic::compileImplcasts the argument to the result type before callingOp::compile. AFloat64argument was lowered withfptoui double to i8and the swap ran on thenarrowed byte, while
applythrowsBAD_ARGUMENTSfor anyAother thanUInt8.compilablewastruefor every argument type; it is nowstd::is_same_v<A, ResultType>, so thecompiled domain equals the domain
applyaccepts and everything else falls through to theinterpreter, as it already did.
UInt8keeps its JIT coverage; wider and big integers lose the samedivergence. This follows
c441505a8ffa8af("Cover all input types in JITintExp2"), the samechange to the same member, and the sibling
__bitWrapperFunc(sameUInt8ResultType, samethrowing
apply) is alreadycompilable = false.bitNotreaches the same lowering for floats and is deliberately not changed: itsapplyneverthrows, 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
isIntegerTyguard incompileis removed, as the cast to the result type already made it unreachable.Workflow [PR]
Sync PR [sync-upstream/pr/117613]
Version info
26.10.1.1152-master(included in26.10and later)