Skip to content

Column-native IN/set constant handling (remove Field) - #113051

Merged
yakov-olkhovskiy merged 5 commits into
masterfrom
valueref-in-set-column-native
Aug 12, 2026
Merged

yakov-olkhovskiy merged 5 commits into
masterfrom
valueref-in-set-column-native

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Aug 3, 2026 •

Copy link
Copy Markdown
Member

Column-native IN/set constant handling, continuing the removal of DB::Field from constant-expression evaluation.

What

  1. convertColumnToType: column-native strict numeric path. The set builder converts values with strict=true (to exclude values not exactly representable in the LHS type), and convertColumnToType previously excluded strict from its column-native fast path, forcing a Field reconstruction for every strict conversion. For native numbers castColumnAccurateOrNull (already used for the default mode) matches convertFieldToType with strict=true exactly; strict only differs for types already excluded from the fast path — Bool and Decimal (where accurate cast rounds 33.33→33.3 instead of rejecting it, so Decimal correctly stays on the Field fallback). Verified by a strict native-number matrix added to gtest_convert_column_to_type.

  2. Make the IN/set builder column-native. 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 rather than inspecting Field::isNull. The dispatch (transform_null_in, Nullable(Tuple) dual interpretation, tuple-vs-set disambiguation) is preserved. Analyzer callers (CollectSets, resolveFunction) pass ConstantNode::getColumn; the legacy ActionsVisitor path evaluates with evaluateConstantExpressionAsColumn.

  3. 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 one castColumnAccurateOrNull instead of a per-member cast, keeping parity with the previous Field path for large IN lists. 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 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 matches the values table function and CAST, on both the analyzer and legacy execution paths. Covered by 04692_bool_tag_faithful_in_set. The incidental fix is kept, not pinned.

Related: #112308

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 a Bool constant on the right-hand side of IN being converted to a String left-hand side as '1'/'0' instead of the canonical 'true'/'false' (now consistent with CAST and the values table function).

Version info

  • Merged into: 26.8.1.1200 (included in 26.8 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d324b31]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) ERROR
Bugfix validation (unit tests) ERROR

AI Review

Summary

This PR rewires constant IN/set construction to stay column-native, adds batch conversion fast paths for the native-numeric hot cases, and keeps the intended Bool text fix on both the analyzer and legacy paths. I re-checked the current diff against the existing review threads and did not find any remaining correctness, safety, or test-coverage issues that warrant new inline comments.

Final Verdict

✅ No blocking findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.80% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.10% +0.10%

Changed lines: Changed C/C++ lines covered: 396/405 (97.78%) · Uncovered code

Full report · Diff report

@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as draft August 3, 2026 02:48
@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d324b31c9 with master dab347c4d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 691.36 MiB 688.37 MiB -2.99 MiB (-0.43%)

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 units

13 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.
The matched translation units cost +2.6 s (+4%) in total before that adjustment.

Job report

yakov-olkhovskiy and others added 2 commits August 3, 2026 14:21
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]>
@yakov-olkhovskiy yakov-olkhovskiy changed the title Column-native IN/set constant handling (remove Field) [WIP] Column-native IN/set constant handling (remove Field) Aug 3, 2026
@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as ready for review August 3, 2026 14:45
@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Aug 3, 2026
Comment thread src/Interpreters/ActionsVisitor.cpp Resolved
@yakov-olkhovskiy

Copy link
Copy Markdown
Member Author

Bugfix validation is false-negative - we are not fixing anything here, we are pinning down conversions.

@KochetovNicolai KochetovNicolai self-assigned this Aug 10, 2026
Comment thread src/Analyzer/SetUtils.cpp
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)

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.

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

@yakov-olkhovskiy yakov-olkhovskiy Aug 11, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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.

Maybe we don't need to remove Field from this file at all. It's an outdated code; we will remove it eventually.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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]>
Comment thread src/Analyzer/SetUtils.cpp Outdated
Comment on lines +144 to +147
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);

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addressed

Comment thread src/Analyzer/SetUtils.cpp Outdated
}
else
{
out->insertFrom(casted_nested, row);

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.

Check we can avoid row-by-row insertFrom call.
I think we can build a proper filter and use IColumn::filter , IColumn::InsertRangeFrom combination.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addressed

@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 556 480 -13.7% <0.0001 Q17 is a plain GROUP BY aggregation with no IN-constant list, so this PR's IN/set-construction rewrite cannot touch its execution path. The -13.7% reads as run-to-run variance.

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
  • StressHouse run: 09d3aed7-0b93-469a-9d98-0b7da4929d30
  • MIRAI run: c35d236a-f70c-4f4c-8873-69ded4d7daf1
  • PR check IDs:
    • clickbench_801677_1786482385
    • clickbench_801774_1786482389
    • clickbench_801881_1786482398
    • tpch_adapted_1_official_802019_1786482462
    • tpch_adapted_1_official_802165_1786482557
    • tpch_adapted_1_official_802307_1786482599

…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]>
@yakov-olkhovskiy
yakov-olkhovskiy added this pull request to the merge queue Aug 12, 2026
Merged via the queue into master with commit ce2fb4e Aug 12, 2026
349 of 355 checks passed
@yakov-olkhovskiy
yakov-olkhovskiy deleted the valueref-in-set-column-native branch August 12, 2026 02:20
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 12, 2026
yakov-olkhovskiy added a commit that referenced this pull request Oct 19, 2026
… 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]>
alexey-milovidov pushed a commit to canhld94/ClickHouse that referenced this pull request Nov 8, 2026
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
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 15, 2026
`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]>
raimannma pushed a commit to raimannma/ClickHouse that referenced this pull request Nov 22, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants