Skip to content

Keep an exact index atom for an injective key transform over a Tuple key - #124831

Merged
fm4v merged 10 commits into
ClickHouse:masterfrom
groeneai:exact-atom-for-injective-key-transform-over-tuple-key
Nov 18, 2026
Merged

fm4v merged 10 commits into
ClickHouse:masterfrom
groeneai:exact-atom-for-injective-key-transform-over-tuple-key

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Index analysis now keeps an exact condition for IN, NOT IN and has on a Tuple column under an injective key expression such as ORDER BY toString(k), so NOT IN and NOT has can skip parts and granules. toString of Time, Time64, DateTime64 and of a QBit of floating-point elements is no longer treated as injective, since distinct values can render to the same string (a Time beyond 999:59:59, a DateTime64 past 9999-12-31, NaN payloads), so GROUP BY, uniq* and index analysis no longer rely on that claim for them.

Description

Follow-up to #118899 (comment).

Closes: #124704
Related: #117238

#118899 lets ORDER BY toString(k) with k Tuple(...) reach index analysis, relaxed every IN atom and declined NOT IN; #96225 moved that block into tryPrepareSetAtom and extended it to has. #117238 made toString's isInjective type-aware, so the folding cases are already relaxed through is_injective.

This PR removes the block: exactness over the re-packed layout follows the transform's injectivity claim. A relaxed complement atom never prunes on its own, since every evaluator sets can_be_false for it before the inversion. Example: k Tuple(Int64, String), ORDER BY toString(k), k NOT IN ((1, 'a')) read Parts: 2/2; it now reads Parts: 1/2.

#117238's list missed values that render alike: Time/Time64 beyond 999:59:59, DateTime64 past 9999-12-31 and QBit NaN payloads. This layout would miscount them, so they are now marked as collapsing. The cost: the GROUP BY/uniq rewrites no longer apply to toString of these types (GROUP BY toString(DateTime64) 3.7x slower on a debug build), and the toString-keyed tables of 05164_key_condition_lossy_constant_not_equals (#118957) now read a DateTime column, so its pruning and lossy-normalization checks stay live. If that DateTime64 pruning matters more than out-of-range values, the DateTime64 part reverts cleanly.

Validation: 05063_key_transform_tuple_key_in_set arms 14-18 cover the example, NOT has, a saturating Time, QBit NaN payloads and a DateTime64 past 9999-12-31; 05227_injective_claims_tostring_datetime_and_tofixedstring covers the new claims.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2753-master (included in 26.11 and later)
  • Backported to: 26.10.7.11

groeneai and others added 5 commits October 9, 2026 04:14
… type-aware

ClickHouse#118899 relaxed `IN` and declined `NOT IN` for every transformed Tuple key
re-packed against the transform input, because `toString` then claimed
injectivity for every type while it folds NaN payloads and fall-back hours.
ClickHouse#117238 made that claim type-aware, so `analyzeKeyExpressionForSetIndex`
already relaxes those atoms through `is_injective`, and a relaxed `NOT IN`
atom never prunes on its own. Removing the block lets an injective
transform such as `toString` of `Tuple(Int64, String)` keep an exact atom.

Follow-up to ClickHouse#118899 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Their text form saturates (`DateTime64` outside `0000-01-01`..`9999-12-31`,
`Time`/`Time64` beyond `999:59:59`), so distinct values render alike, as for
`Date32`. With the re-pack block gone, an exact atom over
`ORDER BY toString(k)` would otherwise miscount `IN` and `NOT IN` for them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The runner turns the setting off in some runs, and then the default-settings line of each pair computes the truth even with the old claim, so the pair would not catch a reverted claim.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`QBit` does not expose its element type to the type walk, so distinct `NaN` payloads, which render alike, were treated as distinct strings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Marking every `DateTime64` as collapsing makes the `!=` atom over `ORDER BY toString(d)` inexact, while `05164_key_condition_lossy_constant_not_equals` checks that it prunes. A `DateTime64` outside `0000-01-01`..`9999-12-31` still renders alike, as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Oct 9, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
Finding Verdict
❌ toString still claimed injectivity for Time and Time64, whose text form saturates beyond 999:59:59, and for a QBit of floats, whose NaN payloads render alike, so removing the block would make IN/NOT IN over ORDER BY toString(k) miscount for such values AGREE, fixed at the claim: all three are marked collapsing in renderingCollapsesDistinctValues, with tests
⚠️ A fixed-offset DateTime64 outside 0000-01-01..9999-12-31 collides the same way (raised twice) AGREE on the mechanism; left to the owner. It needs a stored value and the constant both out of range, as master's scalar ORDER BY toString(d) already does. Marking DateTime64 removes the != pruning that 05164_key_condition_lossy_constant_not_equals checks; the choice is offered in the description
⚠️ The new 05227 pairs could pass with the claim reverted, because the runner turns optimize_injective_functions_inside_uniq off in some runs AGREE, fixed: the default-settings line of each pair pins it to 1
⚠️ Bool bytes other than 0/1 and unknown Enum values written through RowBinary DISAGREE: a stored Bool byte other than 0/1 is itself the defect (#124074), and over the type's values toString(Bool) is injective. An unknown Enum value throws instead of rendering, so it never reaches this layout

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. k Tuple(Int64, String), ORDER BY toString(k), two parts, EXPLAIN indexes = 1 ... WHERE k NOT IN ((1, 'a')): master prints Condition: true, Parts: 2/2; this PR prints Condition: (toString(k) notIn 1-element set), Parts: 1/2. Arm 14 of 05063.
b Root cause explained? The removed block worked around toString claiming injectivity for every type. #117238 made the claim type-aware, and analyzeKeyExpressionForSetIndex already relaxes non-injective transforms, so the block only removed exactness from injective ones and declined NOT IN.
c Fix matches root cause? Yes. The workaround is deleted; exactness on this layout follows isInjective as on every other layout, and the claim is corrected at its source for Time, Time64 and QBit of a floating-point element. DateTime64 keeps master's time-zone rule, because 05164 pins exact pruning over ORDER BY toString(d) for it.
d Test intent preserved / new tests added? Arms 1-13 keep their queries; arm 9 now expects the relaxed notIn atom; new arm 14 asserts the exact atom with a Parts: oracle that a relaxed atom fails.
e Both directions demonstrated? Master binary fails arms 9 and 14, this PR passes. Mutants: relaxing the layout unconditionally fails only arm 14; dropping the is_injective relaxation fails the NaN and fall-back-hour arms 5 and 6. Without the claim fix, arms 15 and 16 and the pinned Time, Time64 and QBit lines of 05227 fail (master fails those 05227 lines too), and each pinned line keeps the optimization live under randomization. Marking every DateTime64 as collapsing makes the four pruning checks of 05164 throw TOO_MANY_ROWS; with master's time-zone rule they pass.
f Fix is general across code paths? The scalar key, packed Tuple set and identity(k) paths already use the same claim (arms 12, 13); primary key, partition pruning, minmax and exact count share this function (arms 7, 10, 5). 517 related tests pass, except 9 rig artifacts that fail identically on a master binary; the 46 QBit tests give identical verdicts with and without the QBit change.
g Fix generalizes across inputs (params/datatypes/wrappers)? Float and NaN, non-fixed-offset date-time, Nullable elements (24-cell transform_null_in x IN/NOT IN matrix vs no-index truth), Tuple(Int64, String); index_granularity 1 and 8192, implicit projections 0/1, trivial count off, query condition cache, parallel replicas. Saturating Time and Time64 values and the NaN payloads of a QBit(Float32, 1) element, which collide under toString, are covered by the claim fix (arms 15, 16 and 05227).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or stored state changes; only how much index analysis prunes.
i Invariants and contracts preserved? An atom is exact only when isDeterministicTransformInjective holds; a relaxed atom still sets can_be_false before the NOT IN inversion; set elements still go through the lossless cast; out.relaxed from key analysis is untouched on every path.

Session id: cron:clickhouse-impl-slot-4:20261008-173703

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2155fe8]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR IGNORED

AI Review

Summary

PR #124831 preserves exact index atoms for injective transforms of Tuple keys and corrects lossy toString injectivity claims for Time, Time64, DateTime64, and floating-point QBit elements. No unresolved findings at 2155fe8ae206c885d721e5cc8a015c16a57b451b; the prior DateTime64 finding is addressed. The three modified regression tests produce their reference output using the current PR binary, and additional nullable-tuple checks agree with full-scan results.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 9, 2026
Comment thread src/Functions/FunctionsConversion.h Resolved
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c461aba

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy, 2/4) / Build ClickHouse master-side build break, not from this PR (which changes FunctionsConversion.h and KeyCondition.cpp): src/Common/Scheduler/Nodes/tests/gtest_throttler_constraint.cpp:25:11: error: use of undeclared identifier 'FifoQueue', the only error in the shard, in a file this PR does not touch. 19 true-master commits and 79 PRs fail this shard since 2026-10-09 00:35Z #124798 (external, open)
Mergeable Check, PR praktika rollups of the row above (Failed: Build (arm_tidy, 2/4), Dropped: 81), no independent failure #124798 (external, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

All check runs completed. The other three arm_tidy shards, Fast test and Style check passed. 81 jobs were dropped behind the shard 2/4 failure, so the functional test matrix has not run on this head yet.

Session id: cron:our-pr-ci-monitor:20261009-070003

groeneai and others added 4 commits October 15, 2026 14:11
…ctive-key-transform-over-tuple-key

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The block guarded the blanket injectivity claim `toString` used to make
for every argument type. That claim is type-aware now and already drives
`is_relaxed` for every set-atom candidate, so the block only cost
exactness for `IN` and `has` over an injective whole-tuple transform such
as `ORDER BY toString(k)` with `k Tuple(Int64, String)`, and declined
complement atoms that are sound when relaxed. The `allow_relaxed_pruning`
parameter of `tryPrepareSetAtom` was used only there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Values past `9999-12-31` render alike, as for `Date32`, so `toString` of
a `DateTime64` is not injective whatever the time zone. `05164` keys its
`toString` tables on `DateTime` columns, so its pruning and
lossy-normalization checks stay live.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On a DateTime key a fractional String spelling does not survive key analysis's conversion, which parses with the basic format (ClickHouse#120113), so the String-spelling checks use the T spelling: both parsers accept it and it still renders back differently. A DateTime64 constant past 9999-12-31 reaches a parallel replica as text and saturates there, so arm 18 runs without parallel replicas, as arm 16 does.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
Finding Verdict
❌ A DateTime64 past 9999-12-31 renders like its neighbours, so the re-packed layout could prune a matching part (raised in earlier rounds and by the bot) AGREE, fixed: DateTime64 of any time zone is marked as collapsing, with a 05063 arm and a 05227 pair; 05164 reads a DateTime column so its pruning checks stay live
⚠️ Arms 15, 16 and 18 assert counts only, so they would pass if the atom were declined instead of relaxed DISAGREE: this PR only decides whether such an atom is exact, and the counts fail with an exact one (measured). Relaxed versus declined comes from unchanged code (arm 9 checks it for Float64), and a relaxed NOT IN atom never prunes anyway
💡 The comments that turn parallel replicas off in arms 16 and 18 describe remote-constant bugs that are already fixed Partly: a QBit constant is now sent to a replica exactly (05353_qbit_constant_sent_to_remote), so the arm 16 setting is probably no longer needed; it is harmless. A DateTime64 past 9999-12-31 still arrives saturated (measured with remote()), so arm 18 keeps it

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. k Tuple(Int64, String), ORDER BY toString(k), two parts, EXPLAIN indexes = 1 ... WHERE k NOT IN ((1, 'a')): master prints Condition: true, Parts: 2/2; this PR prints Condition: (toString(k) notIn 1-element set), Parts: 1/2. Arms 14 (NOT IN) and 17 (NOT has) of 05063. The reproducer of #124704 gives 5 wrong pairs on master and 0 here.
b Root cause explained? The removed block worked around toString claiming injectivity for every type. #117238 made the claim type-aware and set-atom construction already relaxes non-injective transforms, so the block only removed exactness from injective ones. The claim still missed renderings that collide: Time/Time64 saturate beyond 999:59:59, DateTime64 clamps the rendered year to 0000..9999, and a QBit of floats hides NaN payloads from the type walk.
c Fix matches root cause? Yes. The workaround is deleted together with its now-unused parameter; exactness on this layout follows isInjective as on every other layout, and the claim is corrected at its source for Time, Time64, DateTime64 and QBit of a floating-point element. No type-keyed guard is added to key analysis.
d Test intent preserved / new tests added? Arms 1-13 of 05063 keep their queries; arm 9 now expects the relaxed notIn atom; arms 14 and 17 assert the exact atom with a Parts: oracle that a relaxed atom fails; arms 15, 16 and 18 assert counts over colliding renderings. 05164's reference is unchanged; its toString-keyed tables read a DateTime column, and both of its guards stay live.
e Both directions demonstrated? With the block (master merged in): arms 9, 14, 17 fail. Block removed, DateTime64 still claimed injective: arm 18 fails (2, 0, 0) and so does the pinned DateTime64 line of 05227. This PR: all pass. Mutants on 05164: reporting every normalization as exact fails exactly its lossy lines; disabling the String-constant rescue fails exactly its T-spelling pruning line.
f Fix is general across code paths? IN, NOT IN, has and NOT has share the changed function (arms 14, 17); the scalar key, packed Tuple set and identity(k) paths already used the claim (arms 12, 13); primary key, partition pruning, minmax and exact count share this function (arms 7, 10, 5). 613 related tests give the same verdicts before and after the block removal and the DateTime64 change, except the two intended tests.
g Fix generalizes across inputs (params/datatypes/wrappers)? Float and NaN, non-fixed-offset date-time, Nullable elements (36-cell transform_null_in matrix vs no-index truth), Tuple(Int64, String); index_granularity 1 and 8192, implicit projections 0/1, parallel replicas (local plan 0/1, max_threads = 1), a Replicated database, 50 randomized runs each. Saturating Time/Time64, a DateTime64 past 9999-12-31 and QBit(Float32, 1) NaN payloads are covered by the claim fix (arms 15, 16, 18 and 05227).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or stored state changes; only how much index analysis prunes and which toString calls the injective GROUP BY/uniq rewrites apply to.
i Invariants and contracts preserved? An atom is exact only when isDeterministicTransformInjective holds; a relaxed atom still sets can_be_false before every NOT IN/notHas inversion; set elements still go through the lossless cast; key analysis's own relaxation is untouched on every path.

Session id: cron:clickhouse-impl-slot-6:20261015-153300

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e362a8f

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05345_text_index_prewhere_read_step_order flaky, not from this PR (it changes key analysis for injective transforms over a Tuple key, not text indexes): the known read_order_index_first 0 -> 1 diff in the ParallelReplicas lane; it failed on 68 PRs and 12 times on master in the last 30 days #125892 (mine, open)
Performance Comparison (arm_release, master_head, 1/6) / sparse_column_index_runs #5 not from this PR (this query is an ARRAY JOIN over lazily replicated columns): a master regression that arrived with master 06a0224 (#124727). Master's own run of that commit shows 37 ms -> 53 ms (this PR: 39 ms -> 51 ms), as do 6 other PRs whose CI started in the same 30 minutes a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the rows above #125892 (mine, open) and the fix task above

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261015-200013

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release, master_head, 1/6) / sparse_column_index_runs #5 row of the CI finish ledger above (and so for its Mergeable Check, PR rollup row): #126160. It restores the per-output-block cut of lazily replicated ARRAY JOIN passengers that #124727 removed.

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Dear @nihalzp, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@nihalzp nihalzp self-assigned this Nov 9, 2026
@fm4v
fm4v added this pull request to the merge queue Nov 18, 2026
Merged via the queue into ClickHouse:master with commit 23fe1fa Nov 18, 2026
352 of 356 checks passed
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 18, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 18, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 18, 2026
Backport #124831 to 26.10: Keep an exact index atom for an injective key transform over a Tuple key
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @nihalzp @fm4v — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@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... groeneai-origin-review-human PR origin: human review feedback on a groeneai PR pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

toString injectivity misses saturating Time/DateTime64 and QBit NaN

7 participants