Repository navigation
Column-native IN/set constant handling (remove Field) - #113051
Conversation
The set builder (`IN`) converts values with `strict=true` (to exclude values not exactly representable in the LHS type). `convertColumnToType` excluded `strict` from its column-native fast path, so every strict conversion fell back to reconstructing a `Field` + `convertFieldToType`. For native numbers this exclusion is unnecessary: `castColumnAccurateOrNull` (already used for the default mode) matches `convertFieldToType(strict=true)` exactly - both reject out-of-range and inexact conversions. `strict` only rejects extra cases for types already excluded from the fast path - `Bool` (e.g. 10 is not a valid `Bool`) and `Decimal` (scale reduction, where `castColumnAccurateOrNull` rounds `33.33` to `33.3` instead of rejecting it - and `Decimal` is not a native number, so it stays on the `Field` fallback). So drop `strict` from the fast-path gate (it's no longer a parameter). This makes strict native-number conversions `Field`-free and unblocks a column-native `IN`/set builder. Verified by extending `gtest_convert_column_to_type` with a strict native-number matrix (int/float narrowing, overflow, sign, int->float precision loss) plus Decimal-strict controls that must stay on the fallback. Part of removing DB::Field. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [d324b31] Summary: ❌
AI ReviewSummaryThis PR rewires constant Final Verdict✅ No blocking findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 396/405 (97.78%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units13 translation units recompiled, 67 s compile time in total, 13 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
Migrate the constant `IN` / set-building path off `DB::Field`.
`getSetElementsForConstantValue` now takes the right-hand side as a
`ColumnPtr` instead of a `Field`, and `createBlockFromCollection` iterates the
collection's member columns (`Array` elements as rows, `Tuple` elements as
subcolumns) instead of `Array`/`Tuple` of `Field`. Per-element conversion goes
through `convertColumnToType` (strict) via a new `convertColumnToTypeCheckEnum`,
the column twin of `convertFieldToTypeCheckEnum`; the not-representable vs
genuine-NULL distinction uses `convertColumnToType`'s null channel (`{}` vs a
size-1 NULL column) instead of inspecting `Field::isNull`. The dispatch
(`transform_null_in`, `Nullable(Tuple)` dual interpretation, tuple-vs-set
disambiguation) is preserved, with `Field` value inspections replaced by
column-native ones (`isNullAt`, homogeneous element-type checks).
Callers:
- analyzer (`CollectSets`, `resolveFunction`) pass `ConstantNode::getColumn`
instead of `ConstantNode::getValue` (no `Field` materialization);
- legacy `ActionsVisitor` evaluates set elements with
`evaluateConstantExpressionAsColumn` and assembles the collection column
directly (`buildCollectionColumnAndTypeFromASTFunction`).
Because the set is now built with `convertColumnToType` (tag-faithful for
`Bool` since #112308), a `Bool` set element converted to a textual left-hand
type is now the canonical `'true'`/`'false'` rather than the numeric collapse
`'1'`/`'0'` produced by the old `Field` path (`IColumn::get` erased the `Bool`
tag to `UInt64` before `convertFieldToType`). This is an incidental fix, kept
rather than pinned, on both the analyzer and legacy paths; regression test
`04692_bool_tag_faithful_in_set` covers it. This matches the `values` table
function and `CAST` behavior.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add a fast path to `createBlockFromCollection` for the common case of a single native-number key (`x IN (1, 2, ...)` / `x IN [1, 2, ...]`): when the target and every set member share a plain native-number type, convert them all with one `castColumnAccurateOrNull` over a gathered column instead of a per-member cast. This avoids per-element CAST-function invocation overhead for large `IN` lists that the per-member path (a size-1 `convertColumnToType` per element) would otherwise incur, keeping the column-native builder at parity with the previous `Field` path. The cast is element-wise, so per-row results and their order are identical to the per-member loop; only values not exactly representable in the target (NULL in the accurate-cast result) are dropped, matching the strict per-member conversion into the non-nullable native target. This is exactly the native-number equivalence between `castColumnAccurateOrNull` and strict `convertColumnToType` that `gtest_convert_column_to_type` pins. Anything else - `Bool`/`Decimal`/`Enum`/`Nullable`/wide-int targets, mixed member types, empty sets - returns to the per-member loop, so no reordering or behavior change can leak in. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Bugfix validation is false-negative - we are not fixing anything here, we are pinning down conversions. |
| bool hasNullInCollection(const Field & rhs, const WhichDataType & rhs_which_type) | ||
| /// Build set members from an `Array` collection column (size-1, holds one array): the members are the | ||
| /// array's elements, all of the array's nested type. | ||
| SetMembers membersFromArray(const ColumnPtr & rhs_column, const DataTypePtr & array_type) |
There was a problem hiding this comment.
That looks inefficient. If we already had Array column, it should has single type, and no need to unpack in and it into SetMembers.
Please, check why it's needed
There was a problem hiding this comment.
I optimized it, but we still need it for not a native-number (String/Date/Decimal/Enum/Bool, Nullable(Tuple) ) which are still converted through Field - it is planned for removal on next phase. Also it is used for consistency of issuing errors for cases of inconsistent shapes on the right side of IN
| namespace | ||
| { | ||
| std::pair<Field, DataTypePtr> buildCollectionFieldAndTypeFromASTFunction( | ||
| /// Build the constant right-hand side of `IN` as a single-row column plus its exact type, without |
There was a problem hiding this comment.
Maybe we don't need to remove Field from this file at all. It's an outdated code; we will remove it eventually.
There was a problem hiding this comment.
I think it's better to keep it - it shares getSetElementsForConstantValue() with new code - it will cost additional wrapper, then it also shares bug fix in this PR for Bool - which is good, and also we don't know which lands first - removal of an old analyzer or Field
KochetovNicolai
left a comment
There was a problem hiding this comment.
Overall LGTM, but please fix membersFromArray
An `Array` RHS is homogeneous, so its elements are already laid out as contiguous key column(s) with one nested type - the array's data column for a single key, or the sub-columns of its data `Tuple` for a multi-column key. Convert those columns directly instead of routing through `membersFromArray`, which cut every element into a size-1 column (and, for the native fast path, then gathered them back). `build_from_array` now tries `tryBuildFromNativeArray` first: - single scalar key (`x IN [...]`), including a `Nullable` element type and/or a `Nullable` key: `buildSingleNativeKey` does one accurate cast over the whole key column, honoring the per-row NULL policy (`transform_null_in`) exactly as the general per-element loop; - multi-column key over an array of tuples (`(a, b) IN [(1, 2), (3, 4)]`): `buildNativeKeysBatch` casts each of the k contiguous key columns once and keeps a row iff it is not an array-element NULL and every key is representable. Everything else keeps the general `SetMembers` path and its exact errors: non-native element types (still per-value via `convertColumnToType`; whole-column once B3 lands), `Nullable(Tuple)`, and shape/arity mismatches. Tuple RHS collections stay on the general path too - their elements live in separate, independently typed sub-columns, so they are neither contiguous nor guaranteed homogeneous and cannot be batched this way. Results and order are identical to the per-element path (same element-wise `castColumnAccurateOrNull`), verified by a differential check of `x IN [array]` against the tuple general path across the nullable / `transform_null_in` / not-representable matrix on both the analyzer and legacy execution paths. Co-Authored-By: Claude Opus 4.8 <[email protected]>
| out.reserve(out.size() + null_map.size()); | ||
| for (size_t i = 0, size = null_map.size(); i < size; ++i) | ||
| if (!null_map[i]) | ||
| out.insertFrom(nested, i); |
There was a problem hiding this comment.
Looks like this can be done by IColumn::filter
Also I am 95% sure out is empty. Consider if we can return ColumnPtr or std::optional or something.
| } | ||
| else | ||
| { | ||
| out->insertFrom(casted_nested, row); |
There was a problem hiding this comment.
Check we can avoid row-by-row insertFrom call.
I think we can build a proper filter and use IColumn::filter , IColumn::InsertRangeFrom combination.
|
📊 Cloud Performance Report ✅ AI verdict: This PR rewrites IN/set constant construction to be column-native (a query-analysis/planning-time path) with a batch-cast fast path for native-number members. The two flagged ClickBench queries, Q17 and Q18, are both plain GROUP BY aggregations with no IN-constant list, so neither exercises the changed code. The flagged Q17 improvement (-13.7%) is downgraded to not-sure as off-path variance, and Q18's envelope suppression (-5.2%) is consistent with the diff. No query here plausibly attributes a delta to this change. clickbenchFlagged queries (1 of 43)
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. tpch_adapted_1_official🟢 No significant changes Debug info
|
…tFrom Address review: the native-number set builders converted each row and then appended the kept ones with a per-row `insertFrom` (a virtual call per element). Build the keep mask once and select rows with a single vectorized `IColumn::filter` per output column instead. - `tryConvertNativeNumberMembersBatch` (a `Tuple` collection gathered into one key column) now casts once and returns the not-representable rows filtered out, as a `std::optional<ColumnPtr>`, rather than appending into an always-empty `out` - `appendNativeBatch` is gone. - `buildSingleNativeKey` builds the keep filter (and, for a `Nullable` target, the result null-map) in one pass, then applies one `filter`, wrapping the result in `ColumnNullable` when needed. - `buildNativeKeysBatch` builds one shared keep filter across the k key columns and filters each once. Pure performance/cleanup: the keep decision and row order are unchanged (same element-wise `castColumnAccurateOrNull`), verified by the differential check of `x IN [array]` against the tuple general path across the NULL / transform_null_in / not-representable matrix on both the analyzer and legacy paths. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… not representable
A `Date`/`Date32` whose midnight is outside the `UInt32` range of `DateTime`
was stored truncated modulo 2^32, so an `IN` constant matched an unrelated row
while `=` correctly matched nothing:
-- dt DateTime('UTC')
dt IN (toDate32('0000-01-01')) -- matched 2257290240 (2041-07-12)
dt IN (toDate('2149-06-06')) -- matched 1367256704 (2013-04-29)
`convertFieldToType` keeps the exact timestamp, but a `DateTime` column can only
hold it truncated. The `Date` maximum case is wrong in 26.7.34.3, 26.8.30.8 and
26.9.21.9; the pre-epoch `Date32` case is a regression in 26.8, the first release
with #113051, which builds `IN` sets
through `convertColumnToType`.
Treat such a value as not representable, the same range check as `UInt64` ->
`DateTime` (#117244): it is left
out of the set, and `values` rejects it with `ARGUMENT_OUT_OF_BOUND`. A `Date`
before the epoch is unaffected, since `fromDayNum(DayNum)` saturates.
Raised by the AI review on #115047.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since the column-native set builder (ClickHouse#113051), every member of a `Tuple` collection on the right-hand side of `IN` is converted with a separate `castColumnAccurateOrNull`, which builds a CAST function per member. The existing batch path only applied when every member had the same exact type, which is never the case for a literal list crossing 255 or 65535 (`UInt8`/`UInt16`/`UInt32` literals). A direct dictionary sends `WHERE id IN (...)` with up to 65409 literals per block, so `dictGet` became up to 2x slower. Group the members by type and cast every native-number group once, preserving the member order; other groups keep the per-member path. The multi-key path converts key by key over the tuples still alive, so the per-tuple short-circuit of the previous loop is preserved. Also let `convertColumnToTypeOrNull` return the value untouched when the source and target types are equal, as `convertFieldToType` does. Local timings (release build, 50k-row source, best of 5): simple key `value_int` 75k lookups: 0.332 s -> 0.161 s; complex key `value_int` 75k lookups: 0.827 s -> 0.669 s. Closes: ClickHouse#115803 Related: ClickHouse#113051 Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=29cf83dac1355231265f4893603d31dfcfb577f1&name_0=MasterCI&name_1=Performance%20Comparison%20%28arm_release%2C%20release_base%2C%203%2F6%29 Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_015vE8zKDB5gVhhkVvCHtXh8
`tryConvertNativeNumberMembersBatch` builds a single native-number key set
from a constant `Tuple` with one accurate cast, and must only do so when
every member is a plain native number. It applied `nativeBatchApplicable`
(which excludes `Bool`) to the first member only and accepted the others
by `IDataType::equals`, which ignores custom type names, so `Bool` equals
`UInt8`. A `Bool` member holding a raw byte such as 2 (from `reinterpret`)
after a `UInt8` member was then cast as `UInt8` and kept the byte, while
the per-member path normalizes it to `true`:
n IN (0, reinterpret(toUInt8(2), 'Bool')) -- rows 0, 2
n IN (reinterpret(toUInt8(2), 'Bool'), 0) -- rows 0, 1
Apply `nativeBatchApplicable` to every member, so a tuple with a `Bool`
member takes the per-member path, as it already did when the `Bool` member
came first. Tuples of plain numbers keep the batch path. The `Array` entry
points already check their single element type.
Affects 26.8 and later (introduced with the batch path in ClickHouse#113051).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ding a constant IN set A literal gets the narrowest type that holds it, so the members of a literal `IN` list such as ids 0..29997 mix UInt8 and UInt16. The batch path of tryConvertNativeNumberMembersBatch (ClickHouse#113051) required one member type, so such lists converted every value through convertColumnToTypeCheckEnum (a new one-row column per value) and insertRangeFrom. Members that are all native integers are now gathered into a ColumnUInt64 (all unsigned) or a ColumnInt64 (signed, or unsigned narrower than 64 bit). Both hold every member value exactly, and castColumnAccurateOrNull decides representability from the value as the strict per-member conversion does (accurate::convertNumeric), so the set is unchanged. Floats mixed with other members and UInt64 together with signed members keep the per-member loop. Measured on a release build, plain master, one toggle binary, 12 fresh-process blocks (PR / master, 95% CI): 10000 UInt64 keys 0..29997 0.952 (0.926-0.979), with use_statistics = 0 0.935 (0.911-0.960), the new set_index.xml query 0.935 (0.907-0.964); 15 controls within noise. The per-value conversion was 6.5% of CPU samples for the 10000-key query and 0 after. The String-list gather proposed in ClickHouse#133467 removed its per-value conversion (5.1% of samples) but was not measurably faster end to end (0.973 (0.932-1.016)), so it is not included. Closes ClickHouse#133467 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Column-native
IN/set constant handling, continuing the removal ofDB::Fieldfrom constant-expression evaluation.What
convertColumnToType: column-nativestrictnumeric path. The set builder converts values withstrict=true(to exclude values not exactly representable in the LHS type), andconvertColumnToTypepreviously excludedstrictfrom its column-native fast path, forcing aFieldreconstruction for every strict conversion. For native numberscastColumnAccurateOrNull(already used for the default mode) matchesconvertFieldToTypewithstrict=trueexactly;strictonly differs for types already excluded from the fast path —BoolandDecimal(where accurate cast rounds33.33→33.3instead of rejecting it, soDecimalcorrectly stays on theFieldfallback). Verified by a strict native-number matrix added togtest_convert_column_to_type.Make the
IN/set builder column-native.getSetElementsForConstantValuenow takes the right-hand side as aColumnPtrinstead of aField, andcreateBlockFromCollectioniterates the collection's member columns (Arrayelements as rows,Tupleelements as subcolumns) instead ofArray/TupleofField. Per-element conversion goes throughconvertColumnToType(strict) via a newconvertColumnToTypeCheckEnum(the column twin ofconvertFieldToTypeCheckEnum); the not-representable vs genuine-NULL distinction usesconvertColumnToType's null channel rather than inspectingField::isNull. The dispatch (transform_null_in,Nullable(Tuple)dual interpretation, tuple-vs-set disambiguation) is preserved. Analyzer callers (CollectSets,resolveFunction) passConstantNode::getColumn; the legacyActionsVisitorpath evaluates withevaluateConstantExpressionAsColumn.Batch accurate cast for a single native-number key. For the common
x IN (1, 2, ...)/x IN [1, 2, ...]case, when the target and every member share a plain native-number type, all members are converted with onecastColumnAccurateOrNullinstead of a per-member cast, keeping parity with the previousFieldpath for largeINlists. The cast is element-wise, so results and order are identical to the per-member loop.Behavior change (bug fix)
Because the set is now built with
convertColumnToType(tag-faithful forBoolsince #112308), aBoolset element converted to a textual left-hand type is now the canonical'true'/'false'rather than the numeric collapse'1'/'0'produced by the oldFieldpath (IColumn::geterased theBooltag toUInt64beforeconvertFieldToType). This matches thevaluestable function andCAST, on both the analyzer and legacy execution paths. Covered by04692_bool_tag_faithful_in_set. The incidental fix is kept, not pinned.Related: #112308
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
Boolconstant on the right-hand side ofINbeing converted to aStringleft-hand side as'1'/'0'instead of the canonical'true'/'false'(now consistent withCASTand thevaluestable function).Version info
26.8.1.1200(included in26.8and later)