Skip to content

Do not treat a key range as exact when the constant is a signed zero - #117722

Merged
alexey-milovidov merged 9 commits into
masterfrom
fix-key-condition-signed-zero-exactness-117543
Oct 2, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
fix-key-condition-signed-zero-exactness-117543

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

When the primary key is a transform of a column, KeyCondition::canConstantBeWrappedByDeterministicFunctions pushes the constant of an equality through the transform and treats the resulting key atom as exact if the transform is injective. IEEE equality does not distinguish -0.0 from +0.0, but an injective transform does: toString(-0.0) is '-0' and reinterpretAsUInt64(-0.0) is not zero. The key atom then covers only one of the two zeros:

CREATE TABLE t (f Float64) ENGINE = MergeTree ORDER BY toString(f) SETTINGS index_granularity = 1;
INSERT INTO t VALUES (-0.0), (-0.5), (0.0), (2.0);

SELECT count() FROM t WHERE f = 0.0;                               -- 1, wrong
SELECT count() FROM t WHERE f = 0.0 SETTINGS use_primary_key = 0;  -- 2, correct

f != 0.0 was wrong in the other direction: the exact atom let the -0.0 row be counted without being filtered, returning 3 instead of 2.

The rewrite is now kept only when the transform maps both zeros to the same value, or when the constant does not reach the transform as one of them, so a non-zero constant keeps its exact single-granule lookup (asserted by the test).

Closes: #117543

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 to CHANGELOG.md):

Fixed wrong results for f = 0.0 and f != 0.0 over a float column when the primary key is an injective transform of it (for example ORDER BY toString(f)): the index treated the transformed constant as exact, although the transform distinguishes -0.0 from +0.0 while the comparison does not.


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

Version info

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

When the primary key is a transform of a column, `KeyCondition` pushes the constant of
an equality through the transform and treats the resulting key atom as exact if the
transform is injective. IEEE equality does not distinguish `-0.0` from `+0.0`, but an
injective transform does: `toString(-0.0)` is `'-0'` and `reinterpretAsUInt64(-0.0)`
is not zero. The key atom then covers only one of the two zeros, so `f = 0.0` skipped
the granules holding the other one, and `f != 0.0` counted its rows without filtering
them.

The rewrite is now kept only when the transform maps both zeros to the same value, or
when the constant does not reach the transform as a zero, so a non-zero constant keeps
its exact single-granule lookup.

Closes: #117543
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [37d40a0]

Summary: ✅


AI Review

Summary

This PR fixes wrong results when deterministic key rewrites treat -0.0 and +0.0 as interchangeable even though the transformed key distinguishes them. The current head covers the previously raised scalar, tuple, Array, Map, and nested-container cases, and I did not find a remaining correctness, metadata, or test-coverage issue in the changed surface.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 37d40a0.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.40% 79.50% +0.10%

Changed lines: Changed C/C++ lines covered: 74/82 (90.24%) · 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 2, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@zlareb1

zlareb1 commented Sep 2, 2026

Copy link
Copy Markdown
Member

The scalar fix looks right, including declining the rewrite entirely (a merely non-exact transformed point atom would still fail to intersect the '-0' granule). But isFloat(dag.input_type) gates the probe on a scalar float input, and the coverage note on #117543 documents the same over-prune with the zero inside a container key, which this PR (which closes that issue) leaves broken:

CREATE TABLE t3 (k Tuple(Float64, Float64)) ENGINE = MergeTree ORDER BY toString(k) SETTINGS index_granularity = 1;
INSERT INTO t3 VALUES ((-0.0, 1.0)), ((-0.5, 1.0)), ((0.0, 1.0)), ((2.0, 1.0));
SELECT count() FROM t3 WHERE k = (0.0, 1.0);  -- 1, should be 2; k != (0.0, 1.0) gives 3, should be 2

EXPLAIN indexes = 1 shows Condition: (toString(k) in ['(0,1)', '(0,1)']), Granules: 2/4. Tuple is the only container allowed in a sorting key, so a recursive gate (input type contains a float anywhere) plus declining when the constant Field contains a float zero anywhere would close it — enumerating sign-flip combinations of a tuple constant through the DAG is not necessary if the zero-containing case just falls back to a scan.

The same top-level-only blindness applies to NaN inside a tuple, which escapes the Field::isNaN checks at lines 2419/2447/3927 (they only fire for a bare Float64 field): with the same table plus a (nan, 1.0) row, k != (nan, 1.0) returns 3 instead of 4, and k = (nan, 1.0) returns 1 instead of 0 — the exact atom prunes to the '(nan,1)' granule and elides the row filter, returning a row that does not satisfy the predicate.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 37d40a015 with master d046101ce (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.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
alexey-milovidov and others added 2 commits September 10, 2026 11:15
Address review: the bailout was keyed on the transformed image colliding with one of the zero
images, so a non-zero constant lost the previously safe pruning whenever its image collided with
a zero image under a non-injective transform. For `ORDER BY notEquals(reinterpretAsUInt64(f), 0)`,
`WHERE f = 1.0` transforms to the same key value as `-0.0` and fell back to a full scan.

The signed-zero ambiguity exists only when the constant itself is a zero: an equality against any
other constant matches a single float value, which the transformed key identifies just as well as
before. The check is now keyed on that, and only a constant whose value cannot be compared against
zero here (a `String`, which the transform converts to a float itself) still uses the image check.
Note that this is not only about exactness - a relaxed atom is also not allowed to prune a granule
that the original predicate matches - so the bailout does not depend on injectivity.

The test now covers the non-injective transform in both directions: `f = 1.0` keeps its pruning
(verified to be load-bearing against a control binary with the previous check), and `f = 0.0`
reads every granule.

Also fix the test failure in CI: the `marks` estimate for the non-zero constant is `1` with
implicit projections and `2` without, and `optimize_use_implicit_projections` is randomized, so
the assertion is now that the estimate stays below the number of granules in the table, which is
what distinguishes index pruning from a full scan.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 2 commits September 17, 2026 17:41
…a `Tuple` constant

The signed-zero bailout in `KeyCondition::canConstantBeWrappedByDeterministicFunctions`
was gated on `isFloat(dag.input_type)`, so it only covered a scalar float key input.
For `k Tuple(Float64, Float64)` with `ORDER BY toString(k)`, `WHERE k = (0.0, 1.0)` still
built an exact atom on `'(0,1)'` and pruned the granule holding `(-0.0, 1.0)`, which tuple
equality matches, so the query returned 1 row instead of 2 (and `k != (0.0, 1.0)` counted
the row without filtering it).

Walk the key input type and the constant `Field` together, and decline the rewrite when a
zero reaches a float element inside a `Tuple`. The scalar path keeps probing whether the
transform distinguishes `+0.0` from `-0.0`; for a tuple the probe would have to enumerate
every combination of signs of the zero elements, so the index simply does not answer the
predicate. A zero at a non-float element, and any tuple constant without a zero, keep
their pruning.

The tuple-carried NaN case raised in the same review is already handled by the recursive
NaN check in `KeyCondition::tryParseAtomFromAST`; the new test pins it as well.

Addresses the review threads and the AI review verdict on
#117722.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, both halves are now covered. The tuple-carried zero is handled in c7c1fa9 exactly as you suggest: a recursive gate that declines the rewrite whenever the constant holds a float zero at a float position of the Tuple, without enumerating sign-flip combinations. The tuple-carried NaN is already handled on master since #118944, which made the NaN check in tryParseAtomFromAST recursive (anyFieldSatisfies), so with this branch merged up k = (nan, 1.0) returns 0 and k != (nan, 1.0) returns all rows. Both are pinned in the new test 05227_key_condition_signed_zero_tuple_transform.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 2 commits September 23, 2026 23:53
…m check

The previous version declined every deterministic key rewrite for an `Array`
or `Map` key holding floats, even when the constant has no zero, so
`WHERE a = [2.0]` with `ORDER BY toString(a)` fell back to a full scan.
`constantMayHoldFloatZero` now walks `Array` and `Map` element by element like
`Tuple`, and bails out only for an actual zero at a float position, a shape
mismatch, or another float carrier.

Reuse the `typeContainsFloat` helper that master added for the `NaN` set check
instead of keeping a second copy of it.

The `IN` path does not need the same guard: `IN` compares floats bit-exactly
(`-0.0 IN (0.0)` is 0), so the transformed set `{'0'}` selects exactly the rows
`f IN (0.0)` matches. The new test pins the agreement of the index with a full
scan for `IN`/`NOT IN`, and the `Array`/`Map` cases.

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

Copy link
Copy Markdown
Member Author

🕵 The only red check on the previous head c7c1fa9d7b5a was Stress test (arm_asan_ubsan, s3). It failed on the Shard number is greater than shard count logical error in ClusterProxy::prepareClusterForParallelReplicas, which is unrelated to KeyCondition.
Related: #101325
Related: #113589 (open fix)

New head 3954569b5756 merges master, walks Array/Map constants for a float zero (bot thread adopted), and adds 05243_key_condition_signed_zero_in_and_array_transform. The IN thread is refuted: IN compares floats bit-exactly, so no guard is needed there; replied on the thread.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 2 commits October 2, 2026 12:16
…key transform check

`typeContainsFloat` relies on `IDataType::forEachChild`, which already walks nested types
recursively, so `Array(Tuple(Float64))` and `Map(String, Array(Nullable(Float64)))` are
recognized as float carriers. The test pins this down, as asked in the review.

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

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

This is weird. LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Oct 2, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
Merged via the queue into master with commit 1c2899a Oct 2, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-key-condition-signed-zero-exactness-117543 branch October 2, 2026 23:50
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
@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

Development

Successfully merging this pull request may close these issues.

KeyCondition over-prunes the signed-zero granule for f = 0.0 when the primary key is an injective float transform

3 participants