Skip to content

Fix toString of integer keys skipping rows across digit counts and use the key for toString(key) IN (subquery) again - #130537

Merged
fm4v merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-130315-tostring-key-in-subquery-pruning
Nov 13, 2026
Merged

fm4v merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-130315-tostring-key-in-subquery-pruning

Conversation

@groeneai

@groeneai groeneai commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

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 filters on toString of an integer key, such as toString(key) = '999999999999999999', skipping matching rows when one granule (or one minmax skip index granule) held integers of 15 or more digits with different numbers of digits. toString(key) IN (subquery) (also CAST(key AS String)) over an integer or Date key uses the primary key again when the subquery returns integers (or dates), as before 26.10. Closes #130315.

Description

Closes: #130315
Related: #118957

On 26.3, 26.8 and 26.10, toString(k) = '999999999999999999' over a UInt64 key returns 0 instead of 1 when one granule holds 999999999999999999 and 1000000000000000000. ToStringMonotonicity compared floor(log10(x)) in double, which gives n for x = 10^n - 1 from 15 digits on, so such a range counted as monotonic although its texts are in the opposite order. The digit count is now exact (common::digits10); 0 stays apart from 1..9 as before, because a Bool renders them as configurable strings.

Since #118957 (26.10), toString(k) IN (SELECT <integers>) over an integer sorting key reads every granule, where 26.8 pruned (#130315). #118957 declines a non-String set element over a string column, because IN parses the column ('02' and '2' are both 2) while the index renders the element. When the string is the text that the key's own chain computes from a native integer (toString, CAST/_CAST to String), it holds only canonical numerals, so the set and the index agree; the same holds for Date. The decline now exempts exactly that case; types with a custom serialization (Bool, also inside SimpleAggregateFunction) stay declined. This path needs the exact digit count: 26.8 pruned it with the same wrong result. Reverting #118957 would bring back the wrong results it fixed (s IN (SELECT toUInt8(2)) over a String key holding '02').

Validation: on the issue's setup the first parent of #118957 and this PR select 1186/3668 granules, master 3668/3668, 39 rows on all. Both tests fail on master; every indexed count matches a full-scan countIf, and max_rows_to_read checks pin the pruning, also for 19-digit keys. 50 randomized runs pass.


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

Version info

  • Merged into: 26.11.1.2150-master (included in 26.11 and later)

groeneai and others added 3 commits November 9, 2026 16:50
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]>
The EXPLAIN lines show only that the condition is built; a condition can
be printed while `MergeTreeSetIndex::checkInRange` prunes nothing. Read the
`UInt64` cell under `max_rows_to_read = 100`: the key reads 21 of the 200
rows, a full scan fails with `TOO_MANY_ROWS`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The read-limit check covered only `toString` of a `UInt64` key. `CAST`, a
`String ALIAS` column (reached as `_CAST`), `Nullable` and `LowCardinality`
keys and a `Date` key evaluate ranges through different code, so a printed
condition alone did not prove they prune. Each now has its own
`max_rows_to_read = 100` check over 200 rows; master fails all six with
`TOO_MANY_ROWS`.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-3, head 4140b8a)
  • ❌ Test proved the condition is printed, not that granules are pruned. AGREE: a max_rows_to_read pruning check is added (fix round 1).
  • ❌ The pruning check covered only toString(UInt64); CAST, the ALIAS column, Nullable, LowCardinality and Date reach other range-evaluation code. AGREE: one pruning check per case (fix round 2).
  • Round 3: no findings.
  • 💡 (toString(k), k) IN (SELECT (x, x)) prunes as in 26.8, not as on master: MergeTreeSetIndex keeps one mapping per key column. Pre-existing, separate code; not changed here.
  • 💡 A key that is itself toString(k) still declines the set. Conservative; not the reported shape.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. UInt64 key k = number * 7, 1000 rows, index_granularity = 1: EXPLAIN indexes = 1 ... WHERE toString(k) IN (SELECT toUInt64(70)) shows Condition: true, Granules: 1000/1000 on master, every run.
b Root cause explained? The decline added by #118957 in KeyCondition::tryPrepareSetColumnsForIndex drops any non-String set element over a string column, since IN parses the column into the element type. For the text of a native integer (or Date) computed by the key chain, that parse and the index rendering agree, so a sound atom was dropped.
c Fix matches root cause? Yes. The decline is narrowed at the same place, for exactly that chain shape (toString, CAST/_CAST to String of a native integer or Date), with custom serializations excluded on both sides. No setting, no downstream guard.
d Test intent preserved / new tests added? New test 05616_key_condition_to_string_key_in_subquery. Existing tests unchanged; 05164 still covers the String-key counter-example.
e Both directions demonstrated? Master: the test fails on its 10 EXPLAIN lines and on each of the six max_rows_to_read pruning checks (toString and CAST of a UInt64 key, an ALIAS column, Nullable, LowCardinality and Date keys; TOO_MANY_ROWS, 200 of 200 rows), counts equal. This PR: passes (9 to 45 rows read). Making MergeTreeSetIndex::checkInRange answer "unknown" (condition still printed, nothing pruned) fails the UInt64 pruning check. Removing the custom-serialization exclusion, replacing it with isBool, or dropping CAST/_CAST each makes it fail. Issue setup: 1186/3668 granules with this PR (= first parent of #118957) vs 3668/3668 on master.
f Fix is general across code paths? One entry point serves every IN set atom (primary key, partition key, KeyCondition-based skip indexes). GLOBAL IN, NOT IN, tuples and longer chains (toString(k + 1)) checked; has and deterministic key transforms are not affected.
g Fix generalizes across inputs (params/datatypes/wrappers)? Test matrix: UInt64/UInt32/Int32/Int64 keys, UInt64/Int32/Int8 elements incl. out-of-range ones, Nullable (and transform_null_in = 1 with a NULL element), LowCardinality, Date, CAST, ::, an ALIAS column, the issue's alias form, NOT IN; Bool and SimpleAggregateFunction(any, Bool) controls stay unpruned. DateTime, Date32, big integers, Decimal, Enum, floats, FixedString and String keys keep the decline.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; the exempted shapes behave as in 26.8.
i Invariants and contracts preserved? An exempted atom prunes exactly the rows Set membership rejects; the set is still built and checked for exactness by the unchanged code after the check, and NULL handling is untouched. 50 randomized runs of all 132 *key_condition* tests pass.

Session id: cron:clickhouse-impl-slot-5:20261110-140200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @KochetovNicolai, could you review this and add the can be tested label so CI runs? The #118957 decline of a non-String set element over a string key column now exempts a key chain that renders a native integer (or Date) as text with toString/CAST, where parsing the text and rendering the element agree, so toString(k) IN (SELECT <integers>) prunes granules again (#130315).

@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a55b1fd]

Summary: ✅


AI Review

Summary

This PR fixes incorrect toString index pruning across integer digit counts and restores pruning for integer and Date sets over canonical key text. Reviewed head a55b1fd6f2eac04ace2ba6da9125b0b039156af0; no unresolved findings. The previous decimal-boundary blocker is fixed and its review thread has been resolved. Both added regression tests match their references on the head's CI binary; 720 additional boundary comparisons and 48 control comparisons agree with full scans.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 10, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a55b1fd6f with master 09696fc14 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.87, programs/clickhouse-keeper ×1.13 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.3 s 16.3 s +10.0 s (+157%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.8 s 8.5 s +5.2 s (+155%)
Compile time of recompiled translation units

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

Job report

`ToStringMonotonicity` compared `floor(log10(x))` computed in `double`. From 15 digits up the
logarithm of `10^n - 1` rounds to `n` (and from 16 digits up `10^n - 1` itself rounds to
`10^n`), so a range such as [999999999999999999, 1000000000000000000] was reported as
monotonic although its texts are in the opposite order. Index analysis then mapped the range
to an inverted string range and skipped matching rows: on 26.3, 26.8 and 26.10
`toString(k) = '999999999999999999'` returns 0 instead of 1 when one granule (or a minmax
skip index granule) holds both values, and the `toString(k) IN (subquery)` pruning restored
by the previous commits reaches the same path (found by the automated review of ClickHouse#130537).

Use `common::digits10`. The zero handling is unchanged: 0 stays apart from 1..9, because a
`Bool` renders 0 and 1 as the configurable `bool_false_representation` and
`bool_true_representation`, so counting 0 as one digit would let `toString(b) = 'z'` skip the
`false` row when false is rendered as 'z' and true as 'a'.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Use the primary key for toString(key) IN (subquery) over an integer key again Fix toString of integer keys skipping rows across digit counts and use the key for toString(key) IN (subquery) again Nov 10, 2026
@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 10, 2026
@fm4v
fm4v added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit d6bde77 Nov 13, 2026
189 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 13, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 13, 2026
Backport #130537 to 26.10: Fix `toString` of integer keys skipping rows across digit counts and use the key for `toString(key) IN (subquery)` again
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…ws across digit counts and use the key for `toString(key) IN (subquery)` again

(cherry picked from commit d8d6d32)
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 13, 2026
…-explain-tests

Resolve the conflict in KeyCondition.cpp: master added isTextOfElementValues
(ClickHouse#130537, 79950f0) at the place where this branch adds
keyToSetConversionMayCollapse; keep both.

keyToSetConversionMayCollapse reads the chain's result type, so for
`toString(k) IN (SELECT <integers>)` it sees a String key against an integer
set and would decline the set again, undoing ClickHouse#130537. Apply the same
isTextOfElementValues exemption to it: the chain computes only canonical
numerals (or `Date` text), which the set's cast parses back to one value.

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

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... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

26.10: toString(key) AS key ... WHERE key IN (subquery) prunes fewer marks (regression from #118957)

5 participants