Skip to content

Report a lossy constant normalization as an inexact atom - #118957

Merged
alexey-milovidov merged 20 commits into
masterfrom
key-condition-lossy-constant-118691
Oct 9, 2026
Merged

alexey-milovidov merged 20 commits into
masterfrom
key-condition-lossy-constant-118691

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Index analysis normalizes a comparison constant into the type the key expression reads before applying the key transform, and castColumnWithoutNulls accepted that cast as exact whenever it produced no NULLs. A cast can lose information without producing a NULL: accurateCastOrNull from DateTime64(6) to DateTime64(3) truncates the sub-millisecond digits instead of answering NULL. The truncated constant is then the exact preimage of a real key point, so the notEquals atom excluded that point and the granule - or, with a partition key of the same shape, the whole partition - holding a live row was pruned:

CREATE TABLE t (d DateTime64(3, 'UTC')) ENGINE = MergeTree ORDER BY toString(d);
INSERT INTO t VALUES (toDateTime64('2023-02-01 12:00:00.000', 3, 'UTC'));
SELECT count() FROM t WHERE d != toDateTime64('2023-02-01 12:00:00.000001', 6, 'UTC'); -- 0, the truth is 1

The cast now reports whether it was lossless, by casting back and comparing. A lossy normalization leaves the atom relaxed - the key point it names has more than one preimage, exactly as a non-injective transform does - so notEquals no longer excludes it while equals keeps its pruning.

The set path normalizes its elements the same way, and had the same hole with no key transform involved at all, in both directions (found in review):

CREATE TABLE t (d DateTime64(3, 'UTC')) ENGINE = MergeTree ORDER BY d;
INSERT INTO t VALUES (toDateTime64('2023-02-01 12:00:00.000', 3, 'UTC'));

SELECT count() FROM t WHERE d NOT IN (SELECT toDateTime64('2023-02-01 12:00:00.000001', 6, 'UTC'));
-- 0, the truth is 1: the atom excluded the point the element was truncated to

SELECT count() FROM t WHERE d IN (SELECT toDateTime64('2023-02-01 12:00:00.000001', 6, 'UTC'));
-- 1, the truth is 0: the atom was read as certainly true over that point, so the count came from the
-- part without its rows being filtered

A lossy element now relaxes the set atom - out.relaxed, the mechanism the non-injective transform path already uses - instead of being reported as exact, so neither exclusion survives. The element itself stays in the set: a relaxed atom is a superset of the predicate, so the points the set does not hold still prune. A literal set hides the defect, because a literal is coerced to the type of the left argument before the index sees it, which makes the index and the rows agree by construction.

A String constant does not go through the round trip: the comparison converts the spelling into the type of the other side and compares there (executeWithConstString), so exactness is decided against that conversion rather than against the spelling. '2023-02-01 12:00:00' renders back as '2023-02-01 12:00:00.000' while naming exactly the same key point, and keeps its pruning.

Closes: #118691
Related: #118688

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 rows silently dropped, or counted without being filtered, when a DateTime64 constant of a finer scale than the column is compared with !=, NOT IN or IN: index analysis truncated the constant and treated the truncated value as the exact point the query asked for, pruning the granule or partition that held a matching row.


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

Version info

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

Index analysis normalizes a comparison constant into the type the key
expression reads before applying the key transform, and
`castColumnWithoutNulls` accepted that cast as exact whenever it
produced no `NULL`s. A cast can lose information without producing a
`NULL`: `accurateCastOrNull` from `DateTime64(6)` to `DateTime64(3)`
truncates the sub-millisecond digits instead of answering `NULL`. The
truncated constant is then the exact preimage of a real key point, so
the `notEquals` atom excluded that point and the granule - or, with a
partition key of the same shape, the whole partition - holding a live
row was pruned:

    CREATE TABLE t (d DateTime64(3, 'UTC')) ENGINE = MergeTree ORDER BY toString(d);
    INSERT INTO t VALUES (toDateTime64('2023-02-01 12:00:00.000', 3, 'UTC'));
    SELECT count() FROM t WHERE d != toDateTime64('2023-02-01 12:00:00.000001', 6, 'UTC');
    -- 0, the truth is 1

The cast now reports whether it was lossless, by casting back and
comparing. A lossy normalization leaves the atom relaxed - the key point
it names has more than one preimage, exactly as a non-injective
transform does - so `notEquals` no longer excludes it while `equals`
keeps its pruning. The set-index path has no relaxed form for a single
element (`notIn` would exclude the same point), so a lossy
normalization declines index analysis there.
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [17c7c2b]

Summary: ✅


AI Review

Summary

This PR fixes exactness tracking when constants and set elements are normalized into key space before pruning. On the current head, the follow-up fixes for String spellings, carrier-sensitive Dynamic / Variant membership, and non-String elements over String / FixedString keys are in place, and the added 05164_key_condition_lossy_constant_not_equals stateless coverage exercises the regressions found during review. I did not find any unresolved correctness, safety, or test-coverage issues in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 17c7c2b.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 150/153 (98.04%) · 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 9, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

@alexey-milovidov alexey-milovidov left a comment

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.

It is pedantic, but ok.

@alexey-milovidov alexey-milovidov self-assigned this Sep 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 9, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Sep 10, 2026
@tiandiwonder
tiandiwonder self-requested a review September 10, 2026 00:52
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 8 commits September 12, 2026 17:52
The exactness probe already had the forward cast: the `accurateOrNull` probe that proved every value
fits is that cast, and its null map was just shown to be empty, so its nested column is what a second
`castColumnAccurate` would return. Read that column back instead of casting again.

The probe moves into `castKeptEveryValue`, so the set path can ask the same question about a set
element.

`'007'` read as `7` was the wrong example for the comment. A comparison against a `String` constant
converts the spelling into the type of the other side with `convertFieldToType`, which refuses `'007'`
for a numeric target - `SELECT 7 = '007'` raises `TYPE_MISMATCH` - so such a constant never reaches
index analysis.
`tryPrepareSetColumnsForIndex` normalizes every set element into the type of the key column and
dropped only the elements the cast turned into a `NULL`. A truncated element is not a `NULL`: a
`DateTime64(6)` element of a subquery set becomes the exact preimage of a `DateTime64(3)` key point,
and the set atom then names a point the predicate does not. On a key that needs no transform at all:

```sql
CREATE TABLE t (d DateTime64(3, 'UTC')) ENGINE = MergeTree ORDER BY d;
INSERT INTO t VALUES (toDateTime64('2023-02-01 12:00:00.000', 3, 'UTC'));

SELECT count() FROM t WHERE d NOT IN (SELECT toDateTime64('2023-02-01 12:00:00.000001', 6, 'UTC'));
-- 0, the truth is 1: `notIn` excluded the point the element was truncated to

SELECT count() FROM t WHERE d IN (SELECT toDateTime64('2023-02-01 12:00:00.000001', 6, 'UTC'));
-- 1, the truth is 0: `in` was read as certainly true over that point, so the count came from the
-- part without filtering its rows
```

A literal set hides both, because the literal is coerced to the type of the left argument before the
index sees it, which makes the index and the rows agree by construction.

A set atom does have a relaxed form - `out.relaxed`, which the non-injective transform path already
uses - so a lossy normalization now relaxes the atom instead of being reported as exact. The element
itself stays: a relaxed atom is a superset of the predicate, so the points the set does not hold still
prune. That also lets the transform path keep its index analysis, which the previous commit of this
pull request declined outright for a lossy element.
…son uses

A `String` constant does not name a value in its own domain: the comparison converts the spelling into
the type of the other side and compares there (`executeWithConstString` in `FunctionsComparison.h`),
so it is that conversion, not the spelling, that the predicate is about. Rendering the normalized
constant back into a string judged the spelling instead - `'2023-02-01 12:00:00'` comes back as
`'2023-02-01 12:00:00.000'` - and relaxed an atom that names exactly the point the predicate asks for,
so `ORDER BY toString(d)` lost the `!=` pruning it had before this pull request.

Ask `convertFieldToType`, the conversion the comparison itself performs, whether the normalized
constant is the value the predicate names. The two answers can differ only where the comparison
raises - `'007'` against a numeric column, a date-time string against a `Date` column - and then no
pruning decision matters, because the query does not produce a result at all.

A string-ish key column is left to the round trip: two string-ish types are compared as bytes
(`executeString`), where the padding a `FixedString` target adds really does change the compared value.
The set arms run literal `NOT IN`, subquery `NOT IN`, `NOT has` and `IN` against the `toString(d)`
key and against a bare `ORDER BY d` key, each next to its `countIf` twin. The bare-key subquery arms
are the ones that answered 1 against 2 for `NOT IN` and 1 against 0 for `IN` before the set path
reported a lossy element; the literal arms agree by construction, because a literal set is coerced to
the type of the left argument before the index sees it, and they are here to pin that difference.

Over-reporting a normalization as lossy would silently disable pruning, which no answer can show, so
a new block pins the lossless directions with `max_rows_to_read`: a lost pruning becomes a
`TOO_MANY_ROWS` failure. The statistics pruner, the query condition cache and parallel replicas are
pinned off there, so the granule mask under test is the key condition's own. The lossy constant is
pinned the other way round, as `serverError TOO_MANY_ROWS`.
`castColumnAccurateOrNull` reports a value that does not fit by wrapping its target in `Nullable`, so
the nested column the exactness probe reads back carries the target *without* that `Nullable` - and
for a target that is itself `Nullable` the probe was handed the nested column next to the wrapped
type, which `columnGetNested` refuses:

```sql
SELECT count() FROM test_table_72265_1 WHERE (a > 100) AND ((a % 2) = toUInt128(0));
-- Code: 44. DB::Exception: Illegal column  Nullable(Int8) Int8(size = 1) for DataTypeNullable
```

Every `Nullable` key column read through a deterministic transform raised it: `01739_index_hint`,
`03311_issue_72265`, `03727_tolowcardinality_nullable_cast`, `04006_nullable_partition_minmax_merge`,
`04237_104840_partition_pruner_floor_null_nullable_key` and
`04401_low_cardinality_fixed_string_partition_pruning`.

A `Dynamic` element lost its exact atom for a different reason: `accurateOrNull` cannot wrap a type
that carries its own NULLs, so the probe declined to answer and
`05055_not_has_tuple_layout_and_variant_key_condition` stopped pruning. A `Dynamic` cannot refuse a
value either, though - every value fits one - so there the plain accurate cast is total and its result
answers the question directly.
…-constant-118691

# Conflicts:
#	src/Storages/MergeTree/KeyCondition.cpp
…xact

`05055_not_has_tuple_layout_and_variant_key_condition` lost a granule of pruning
on this branch: `notHas(CAST([2], 'Array(Dynamic)'), k)` over an `Int64` key
answered `Granules: 4/4` instead of `3/4`.

A `Dynamic` keeps the type each value was inserted with, so the element `2` is
held as a `UInt8` there, the cast to the key type makes it an `Int64`, and the
reverse cast returns a `Dynamic` holding `Int64(2)`. `Field::operator==` answers
only for values carried the same way and reported `UInt64(2) != Int64(2)`, so an
exact cast was called lossy and the atom was relaxed for nothing.

Compare two numeric `Field`s the way the comparison functions compare them,
across carriers, and leave every other pair of carriers to the strict answer -
`accurateEquals` cannot compare those at all. A `DateTime64(6)` constant
truncated to `DateTime64(3)` is still reported as lossy: both sides are carried
as a `Decimal64` and the strict comparison already accounts for the scale.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and fixed the Fast test failure.

Conflict resolution (src/Storages/MergeTree/KeyCondition.cpp, against #118688 which landed meanwhile): master's isDirectCastEquivalentToNormalizedCast and its reordering of convertColumnForDeterministicDag - normalize through the key column's type first, and fall back to the direct CAST only for a Dynamic key input - are kept as they are; this branch's castKeptEveryValue helper and the out_cast_is_exact parameter are threaded through both castColumnWithoutNulls call sites.

05055_not_has_tuple_layout_and_variant_key_condition was a real regression of this branch: notHas(CAST([2], 'Array(Dynamic)'), k) over an Int64 key answered Granules: 4/4 where master answers 3/4. A Dynamic keeps the type each value was inserted with, so the element 2 is held as a UInt8, the cast to the key type makes it an Int64, and the reverse cast returns a Dynamic holding Int64(2). Field::operator== answers only for values carried the same way, so it called an exact cast lossy and the atom was relaxed for nothing. The round trip now compares two numeric Fields the way the comparison functions do, across carriers, and leaves every other pair of carriers to the strict answer (accurateEquals cannot compare those at all). A DateTime64(6) constant truncated to DateTime64(3) is still reported as lossy - both sides are carried as a Decimal64 and the strict comparison already accounts for the scale.

Locally against this build: 05055 and 05164 pass, and so do all 78 key_condition/has_to_in tests and 96 of the primary_key/set_index family (the 8 remaining fail only for environmental reasons here - no ZooKeeper, no cluster, no test.hits, no KeeperMap).

The Finish Workflow / new_tests_check.py red was a cascade of the dropped bugfix-validation jobs and should clear with a green Fast test.

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: eafedf6f-5f4c-4e41-9533-f55b971217e3
  • MIRAI run: 31a6c598-0a20-4d80-a602-5d9873176e32
  • PR check IDs:
    • clickbench_158032_1791364612
    • clickbench_158038_1791364612
    • clickbench_158044_1791364612
    • tpch_adapted_1_official_158055_1791364612
    • tpch_adapted_1_official_158067_1791364612
    • tpch_adapted_1_official_158103_1791364612

@tiandiwonder tiandiwonder left a comment

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.

Two blockers; the core change looks right to me otherwise. I checked that the relaxation is applied before the NOT_IN_RANGE / NOT_IN_SET negation in both evaluators, so the widened can_be_false really does become a widened can_be_true and != / NOT IN stop excluding the point — the mechanism does what the description says.

The blockers are the Dynamic equality below, and the new test failing deterministically on the private sync CI: 20 of the 22 new failures on sync-upstream/pr/118957 are 05164_key_condition_lossy_constant_not_equals.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 2 commits September 25, 2026 19:40
…-constant-118691

# Conflicts:
#	src/Storages/MergeTree/KeyCondition.cpp
`IN` asks the `Set`, which hashes and compares the type each `Dynamic` value
carries before the value, and `Set::execute` casts the key into the set's type
with the key column's type as its carrier. The round trip in
`castKeptEveryValue` compares `Field`s, which cannot see a `UInt8` versus a
`UInt64` carrier, so `k IN (SELECT CAST(toUInt8(2), 'Dynamic'))` over an
`Int64` key was reported exact: `IN` answered 1 instead of 0 and `NOT IN`
pruned a live row. `tryPrepareSetColumnsForIndex` now reports such a set as
inexact for `IN`; `has` keeps the round trip, since it compares by value.

Test changes in `05164_key_condition_lossy_constant_not_equals`:
- drop the literal-set `NOT IN` arms: the literal set is coerced to the key
  type before the index sees it, so they do not exercise this change, and their
  row-level answer depends on randomized settings (they failed in private CI);
- pin a `String` subquery element staying inexact for `notIn`;
- pin the `Dynamic` subquery element for `IN` and `NOT IN` (control build
  without the check answers 1 and 1 instead of 0 and 2).

Also note why the `String` rehabilitation uses strict `Field` equality.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
A `Set` over `Variant` is discriminator-sensitive just like one over `Dynamic`:
`Set::execute` casts the key into the set's type, and `ColumnVariant` hashes and
compares the active discriminator before the value. A `Variant` element usually
fails the round trip in `castKeptEveryValue` already, because a `Variant` cannot
be inside `Nullable`, but `canBeSafelyCast` takes a `Variant` to a
`Nullable(String)` key without any round trip. So
`k IN (SELECT CAST(toUInt8(2), 'Variant(UInt8, String)'))` over a
`Nullable(String)` key was reported exact: `IN` answered 1 instead of 0 and
`NOT IN` pruned a live row (1 instead of 2).

The carrier guard in `tryPrepareSetColumnsForIndex` now also covers a set element
type containing a `Variant` anywhere, besides the types with dynamic subcolumns.

Added the `Variant` arm next to the `Dynamic` one in
`05164_key_condition_lossy_constant_not_equals`; a control build with the old
`hasDynamicSubcolumns` guard answers 1 1 1 instead of 0 2 2.

#118957 (review)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 2 commits October 3, 2026 21:22
…tring` key

`IN` over a subquery casts the key into the set's type, so for a string-ish
column it parses the key and many spellings match one element:
`s IN (SELECT toUInt8(2))` matches both `'2'` and `'02'`. The index renders
the element into a single spelling and read every other one as certainly not
in the set, pruning rows the predicate keeps. Relaxing the atom does not help
because a relaxed atom still prunes on the points it holds, so such a set is
not used by the index at all. This is pre-existing, but it is the mirror of
the scalar `String` case this PR handles.

Also adapt the new `applyDeterministicDagToColumn` call for zero probing that
came with the merge of `master` to the extended signature.

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

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

The fix is #124342 (test-only).

The failing tables test_3.reader__fuzz_{2,3,4} are copies of the 05104 readonly reader, made by the server-side AST fuzzer in Stress (ast_fuzzer_any_query = true). Nothing drops them, so after the test's own DROP TABLE writer SYNC deletes the objects, later reads of the copies (the fuzzer, 02046's merge(currentDatabase(), '') FINAL) get No such key. No hard-link refcount is involved. In #124342 the sessions that create these tables in 05104, 05227 and 05228 set ast_fuzzer_any_query = 0, and the sessions that drop them set ignore_drop_queries_probability = 0.

… from the `String` key bailout

A top-level `Dynamic`, `Variant` or `JSON` set element over a `String` / `FixedString` key was
exempt from the bailout for non-`String` elements, so the index was built from the element's
rendered string. But `Set::execute` converts the key into the element type, which is not total
and not a byte comparison: `s IN (SELECT CAST(toDate('2024-01-01'), 'Variant(Date)'))` raises
`CANNOT_CONVERT_TYPE` in the full scan, and `s IN (SELECT CAST('{"a":1}', 'JSON'))` matches
`'{"a" : 1}'` as well. Pruning from the rendered string hid the error or dropped the matching
row. `Dynamic` parses the key as well under `cast_string_to_dynamic_use_inference`. Do not use the
index for such sets, and pin both shapes in the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check is CH Inc sync (tests failed). None of the private failures are related to the KeyCondition change, so I reran the failed jobs of the sync run:

There are no unresolved review threads.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
Merged via the queue into master with commit 9fd0ee1 Oct 9, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the key-condition-lossy-constant-118691 branch October 9, 2026 02:09
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 9, 2026
Master's ClickHouse#118957 made `tryPrepareSetColumnsForIndex` report an inexact set itself, through
`out_is_exact` and a value-level round trip of every element, which is what this branch's own
type-level `set_is_approximate` flag did more coarsely. The conflict is resolved by taking master's
version of that plumbing (signature, both callers, the relaxation conditions and their comments)
and keeping only the decline for a key-to-set cast that can merge two distinct keys, which master
still answers with missing rows (Decimal / DateTime64 scale loss, a temporal target dropping a
component, a collapsing text element inside a Tuple).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai mentioned this pull request Oct 11, 2026
1 task done
cherepasshka pushed a commit to cherepasshka/ClickHouse that referenced this pull request Nov 6, 2026
The Stress test runs the server-side AST fuzzer on every successful
statement, DDL included (`ast_fuzzer_runs = 5`, `ast_fuzzer_any_query = true`).
After `CREATE TABLE reader ... disk(readonly = true, ...)` it creates
`reader__fuzz_N`: more readonly tables over the same `table_disk` root, each
attached with the writer's parts of that moment, and nothing drops them.
The test's `DROP TABLE writer SYNC` then deletes the objects of those parts,
and later reads of the clones in the kept stress database (fuzzed reads,
02046's `merge(currentDatabase(), '') FINAL`) fail with
`S3_ERROR The specified key does not exist` on `data.packed`, which the
stress `No such key` check reports (PR ClickHouse#118957, Stress test (arm_release)).
05227 and 05228 build the same readonly reader over a writer they drop.

In 05228 the reader `DROP` also runs after the writer's drop has finished,
so a reader `DROP` ignored by `ignore_drop_queries_probability` (it becomes a
TRUNCATE of a read-only table and fails with TABLE_IS_PERMANENTLY_READ_ONLY)
leaves a stale reader as well, and an ignored background writer `DROP` makes
the test wait forever in `SYSTEM WAIT FAILPOINT ... PAUSE`. In 05104 and 05227
both drops share one multi-statement block, so an ignored reader `DROP` stops
the block before the writer drop; the pin there keeps the block's drops.

Pin `ast_fuzzer_any_query = 0` in the sessions that create the tables and
`ignore_drop_queries_probability = 0` in the sessions that drop them. Only
the SELECTs of those sessions stay fuzzed; the ALTERs and OPTIMIZE of 05104
run in other sessions and stay fuzzed too.

Measured locally with the Stress fuzzer settings and one fixed database per
run: 05104 left fuzzer clones in 13 of 87 databases before (816 fuzzed clone
CREATEs, the CI error reproduced by the 02046-style read in 4), none after
(0 fuzzed CREATEs in 80 runs); 05228 likewise. In 05227 a clone survives only
when the fuzzer drops the copied UUID clause (19 of 414 reader attempts in
05104 did); none of its 47 did in 10 runs, and after the change it makes no
fuzzed CREATE in 10 runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 13, 2026
Since ClickHouse#118957, `toString(k) IN (SELECT <integers>)` over an integer key `k`
no longer uses the primary key (ClickHouse#130315): `EXPLAIN indexes = 1` shows
`Condition: true` and every granule is read, where 26.8 pruned with
`toString(k) in N-element set`. The same holds for `CAST(k AS String)`,
`k::String`, a `String ALIAS k` column (`_CAST`), `Nullable`/`LowCardinality`
integer keys and a `Date` key with a `Date` set.

ClickHouse#118957 made `tryPrepareSetColumnsForIndex` decline a non-`String` set element
over a string predicate column, because `Set::execute` casts the column into
the element type by parsing, where many spellings name one value (`'02'` and
`'2'`), while the index renders the element into a single spelling. That
premise does not hold when the string column is the text of a native integer
(or of a `Date`) that the key's monotonic chain itself computes: the column
then holds only canonical numerals, `accurateOrNull` of a canonical numeral
into a native integer type gives that number or NULL, and an integer element
renders to the canonical numeral of its own value, so the set and the index
agree exactly.

Keep the decline, except when the chain ends with `toString`/`CAST`/`_CAST`
to `String` of a native integer and the element is a native integer, or both
are `Date`. Types with a custom serialization are excluded on either side:
`Bool` is a `UInt8` that renders as `true` while the key's `'1'` parses to
`true` (also inside `SimpleAggregateFunction(any, Bool)`, which keeps
`SerializationBool` under another name). A `String` key, `FixedString`
targets, `DateTime` and the other types keep the decline.

Reverting ClickHouse#118957 would bring back the wrong results it fixed (for example
`s IN (SELECT toUInt8(2))` over a `String` key holding `'02'`).

Closes ClickHouse#130315

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... 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

4 participants