Skip to content

Fix index analysis dropping the padding of FixedString constants and IN set elements - #123868

Open
raimannma wants to merge 21 commits into
ClickHouse:masterfrom
raimannma:keycondition-fixedstring-constant-padding
Open

raimannma wants to merge 21 commits into
ClickHouse:masterfrom
raimannma:keycondition-fixedstring-constant-padding

Conversation

@raimannma

@raimannma raimannma commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Index analysis converts a constant or an IN set element to the type the key expression reads. Converting a FixedString to String drops its trailing zero bytes, so the converted value compares differently and matching rows were skipped: e.g. s <= toFixedString('abc', 4) with a key assumeNotNull(s), s = toFixedString('abc', 4) with a key cityHash64(s), or s IN (SELECT toFixedString('abc', 4)). The same happened for a FixedString nested in an Array/Tuple/Variant or held by Dynamic. Such conversions are now refused and the analysis falls back to reading.

Related: #123858

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):

Fix wrong results when a FixedString constant or IN set element with trailing zero bytes is compared with a String column through a primary key, partition key or skipping index expression.


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

raimannma and others added 2 commits October 4, 2026 16:35
Index analysis converts a constant or an `IN` set element to the type the key
expression reads. `canBeSafelyCast` treats `FixedString` to `String` as safe,
but the cast drops trailing zero bytes, so the converted value compares
differently: `s <= toFixedString('abc', 4)` with a key `assumeNotNull(s)` became
`key <= 'abc'`, and `s IN (SELECT toFixedString('abc', 4))` became `s IN ('abc')`.
Both pruned rows with `s = 'abc\0'`. Refuse such a conversion at the three
places that do it, so the analysis falls back to reading.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An `Array(FixedString)` set element cast to `Array(String)`, and a `Variant` or
`Dynamic` constant holding a `FixedString`, lose the trailing zero bytes in the
same way. Check the nested types of the source, and refuse the cast only when the
target holds a `String`, so `Dynamic` values cast to numeric or date keys still
prune.

Found by a local codex review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization labels Oct 4, 2026
@GrigoryPervakov GrigoryPervakov added the can be tested Allows running workflows for external contributors label Oct 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f326459]

Summary: ✅


AI Review

Summary

PR #123868, reviewed at f326459f82e5fb10be427b46531521fba8273d2f, prevents index analysis from discarding matching rows when converting padded FixedString constants or set elements, including nested and type-erased values. The current code addresses the prior findings; no unresolved findings remain. Using the PR-head CI binary through clickhouse local, all 45 regression queries matched the reference, and 192 additional comparisons agreed with index pruning enabled and disabled.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 7, 2026
raimannma and others added 2 commits October 7, 2026 13:08
`castMayDropFixedStringPadding` refused every cast from a `Dynamic` value to a
`String` key, because a `Dynamic` may hold a `FixedString`. That also disabled
the index for sets of `Dynamic` values that only hold `String`, which broke
`04510_not_has_function_explain` (`Granules: 2/2` instead of `1/2`).

For set elements, inspect the types the `Dynamic` column actually stores (and
refuse when its shared variant is non-empty). Constants on the other paths are
rebuilt from a `Field`, which loses the `FixedString` type, so they keep the
type-only check. Also switch to `anyInTypeTree`, since `IDataType::forEachChild`
was removed on master.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123868&sha=ffd58fb8b0fc47a348d7c767fe96460b899958a0&name_0=PR&name_1=Fast%20test
PR: ClickHouse#123868

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
raimannma and others added 2 commits October 7, 2026 14:57
…member types

`castMayDropFixedStringPadding` declined index analysis whenever the declared
`Variant`/`Dynamic` wrapper could contain a `FixedString`, even when the
compared values all hold a `String`.

- A `Variant`/`Dynamic` constant is now wrapped by key functions as a value of
  its active member type (`tryGetActiveTypeOfErasedConstant`), since the
  helpers rebuild it from a `Field`, which cannot tell the member apart.
- Set elements of a `Variant` or `Dynamic` type are narrowed to the
  alternatives they occupy (`narrowVariantToOccupiedAlternatives`), also on
  the deterministic key transform path.

`CAST('abc' AS Variant(String, FixedString(4)))` holds the `FixedString(4)`
member, so it is still declined; the test uses `FixedString(2)` to get a
`String` member.

PR: ClickHouse#123868

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ant types

Two problems found by the local reviews of the previous commit:

- `castMayDropFixedStringPadding` declined any cast where the source held a
  `FixedString` anywhere and the target a `String` anywhere, so a
  `Tuple(FixedString(4), String, UInt64)` key lost pruning for a set element
  that only needs its integer widened. The check now pairs the types the way
  `CAST` converts them (`Array`, `Map`, `Tuple` element-wise, each `Variant`
  member) and falls back to the coarse rule only where the mapping is unknown.

- Wrapping a `Variant`/`Dynamic` constant as a value of its active member
  type changed its conversions: `x = CAST(toIPv4(2) AS Dynamic)` against a
  `UInt8` key under `cityHash64(x)` threw `NOT_IMPLEMENTED` from index
  analysis, since `IPv4 -> UInt8` has no accurate-or-null cast. The constant
  keeps its declared type again; its column is built from the active member
  type instead (`createConstantColumn`), so the guard can always judge a cast
  by the column, and the `column_holds_compared_values` flag is gone.

PR: ClickHouse#123868

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

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f326459f8 with master 0a3052562 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

5 object files changed (+38.96 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/KeyCondition.cpp.o 1.72 MiB 1.76 MiB +38.97 KiB (+2.21%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

342 translation units recompiled, 3601 s compile time in total, 342 of them have a recent master baseline.

Job report

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
…only where it matters

`castMayDropFixedStringPadding` stripped `Nullable` and `LowCardinality` from
the type before matching it with `from_column`. `Variant` and `Dynamic`
cannot be inside either wrapper, so the column always was a plain
`ColumnVariant` or `ColumnDynamic`, but the type and the column now visibly
correspond: the narrowing looks at `from_type` itself, and
`castTypeMayDropFixedStringPadding` strips the wrappers on its own.

PR: ClickHouse#123868

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
raimannma and others added 5 commits October 7, 2026 17:12
…members

Only a top-level `Variant` or `Dynamic` set element was narrowed to the
members it holds. One nested in a `Tuple`, `Array` or `Map` was still judged
by its declared members, so a tuple key lost pruning that it had before this
PR: `k IN (SELECT tuple(CAST('abc' AS Variant(String, FixedString(2))), toUInt8(1)))`
read 4/4 granules instead of 1/4.

`castMayDropFixedStringPadding` now walks the column together with the type
pair, so a `Variant` or `Dynamic` at any depth only counts the members it
actually holds. A column that does not match its type is not used, which
falls back to the conservative check.

PR: ClickHouse#123868

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`createConstantColumn` restored the active member type only for a top-level
`Variant` or `Dynamic` constant and rebuilt any other one from its `Field`,
where a nested `Dynamic` holding a `FixedString` becomes a `String`. Since
`castMayDropFixedStringPadding` now trusts nested member columns, that let a
padded value through: with `ORDER BY cityHash64(x)` over `Tuple(String, UInt8)`,
`x = (CAST(toFixedString('abc', 4) AS Dynamic), toUInt8(1))` counted 2 rows
instead of 3.

A constant whose type has a `Variant` or `Dynamic` at any depth is now taken
from its column in the query, which keeps the members; index analysis
declines when that column does not hold the constant.

PR: ClickHouse#123868

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…dstring-constant-padding

# Conflicts:
#	src/Storages/MergeTree/KeyCondition.cpp
#	src/Storages/MergeTree/KeyCondition.h
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
raimannma and others added 4 commits October 13, 2026 16:59
… as `CAST` does

The bare `key <op> const` path converted a composite constant to the common
type with `tryConvertFieldToType` without the padding check, so a `FixedString`
nested in a `Tuple` constant became a single `String` point and pruned rows that
match with the zero-padded comparison. The constant is now checked with
`castMayDropFixedStringPadding` before the conversion.

The tuple branch of `castMayDropFixedStringPadding` now pairs elements as
`FunctionCast::createTupleWrapper` does: by name when both tuples are named and
share a name, otherwise by position. A reordered named tuple no longer falls
back to the conservative check and keeps index analysis.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…type

A constant that already has the common type skipped the padding check. With a
`Tuple(String, UInt8)` partition key, `k = (CAST(toFixedString('abc', 4) AS Dynamic), 1)`
has the common type `Tuple(Dynamic, UInt8)`, so the `FixedString` it holds became a
single point and partition pruning dropped the parts with `'abc'` and `'abc\0\0'`.
The constant is now checked against both the common type and the key type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A comparison and `convertFieldToType` pair the elements of two named tuples by
position, while `CAST` pairs them by name. The check of a bare `key <op> const`
constant paired them by name, so with a `Tuple(a FixedString(4), b String)` key,
`k = CAST(('abc', CAST(toFixedString('def', 4) AS Dynamic)) AS Tuple(b String, a Dynamic))`
missed the `FixedString` compared with `b`, and partition pruning dropped matching parts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rder

A constant pushed through a monotonic or deterministic key transformation is
converted to the key type with `CAST`, which pairs the elements of two named
tuples by name, while the comparison pairs them by position. With an
`ORDER BY cityHash64(k)` key of type `Tuple(a String, b String)`,
`k = CAST(('x', 'y') AS Tuple(b String, a String))` was hashed as `('y', 'x')` and
pruned the row `('x', 'y')`. Index analysis now declines such a constant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
raimannma and others added 2 commits October 14, 2026 11:28
`castReordersTupleElements` treated any `Variant` or `Dynamic` constant as
possibly reordering the elements of a named tuple in the key type, so
`k = CAST(CAST(('x', 'y') AS Tuple(a String, b String)) AS Dynamic)` on an
`ORDER BY cityHash64(k)` key lost index analysis, which 26.9 used. The check
now walks the column with the types, like `castMayDropFixedStringPadding`, and
only counts the members a `Variant` or `Dynamic` actually holds. Both checks
get these members from the new `tryGetHeldVariantMembers`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since the constant keeps the member its `Variant` or `Dynamic` holds, a
key expression that reads a `Dynamic` can see a `FixedString` where the
stored value is a `String`. They compare equal with the trailing zero bytes,
but `CAST(k AS String)` drops them only from the `FixedString`: with
`ORDER BY CAST(k AS String)`, `k = CAST(toFixedString('abc', 4) AS Dynamic)`
pruned the row `CAST('abc\0' AS Dynamic)`, which 26.9 read. The same held for
a `minmax` skip index. Index analysis now declines such a constant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
…ments

The comparison pairs tuple elements by position, while the cast of a constant
to the key's tuple type pairs two named tuples by name. Converting the text
elements of such a constant by position made that cast succeed on swapped
values: with `t Tuple(d DateTime, n UInt8)` and
`t = CAST(('2026-01-01 12:00:00', 1), 'Tuple(n String, d UInt8)')` the index
skipped all 8 matching rows, and a nested `Nullable(Tuple)` element made the
cast throw `TYPE_MISMATCH`, where master declines the transform because the
text does not parse as `UInt8`. A tuple level whose text was converted and whose
names differ from the key's is now declined, so the constant pairs with the key
as on master; named constants with the key's own names are still normalized.
05402 covers a same-order, a reordered and a nested reordered named constant.

A named constant without text whose names reorder the key's elements is left
as it is: its name-mapped cast is the separate finding of ClickHouse#96225 that ClickHouse#123868
addresses.

Found by the second-model review of the merge with master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…dstring-constant-padding

`KeyCondition` now pushes a constant through several key-wrapping recipes and
keeps the typed column of the constant, so `createConstantColumn` is gone and
the direct comparison takes the column from `ComparisonAtomCandidate`. Master
declines every key transform that reads a `Dynamic`, `Variant` or `JSON`, which
makes `variantMayHoldFixedString` unreachable; it is removed, together with the
check of `05322` that a `Dynamic` key keeps index analysis, which failed in
`Fast test`.

`tryGetHeldVariantMembers` now also returns the types held in the shared variant
of a `Dynamic`, so a `Dynamic(max_types = 0)` constant holding an `Enum` keeps
index analysis (`05221_key_condition_typed_constant_pruning`).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123868&sha=f11c1bd2fcd67b3f6a150c3738d32a0f41d19f6b&name_0=PR&name_1=Fast%20test
PR: ClickHouse#123868
`tryGetHeldVariantMembers` decodes each value of the shared variant instead of
looking up the discriminator of every row. A `Map` is walked as its nested
`Array(Tuple(keys, values))`, which pairs the same elements. Test a `Dynamic`
whose value is in its shared variant, and a `Map` key.
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026

This branch has not been deployed

No deployments
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-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants