Skip to content

Fix a lost row when a signed-zero constant is pushed through a transformed sorting key - #117611

Open
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:keycondition-signed-zero-constant
Open

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:keycondition-signed-zero-constant

Conversation

@groeneai

@groeneai groeneai commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #117543
Related: #115970

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 a lost row when a floating-point column is filtered with a zero constant and the sorting key, partition key or a minmax index applies a transform to that column, for example ORDER BY toString(f) with WHERE f = 0. -0.0 and 0.0 compare equal but toString maps them to different key values, so the primary key dropped the granule holding the other spelling. Closes #117543.

Description

A filter on a zero silently returned fewer rows than a full scan when the sorting key, partition key or a minmax index transformed the column f:

CREATE TABLE t (f Float64) ENGINE = MergeTree ORDER BY toString(f)
    SETTINGS index_granularity = 1;
INSERT INTO t VALUES (-0);
SELECT count() FROM t WHERE f = 0;   -- 0, expected 1

Root cause: over a transformed key, analysis pushes the constant through the transform and uses the result as a range. -0. and +0. compare equal but are distinct values, so a transform reading the bit pattern maps them apart, and a range built from one misses the mark holding the other. Exactness is not the lever: ORDER BY cityHash64(f) is already relaxed and still loses the row, because relaxing widens can_be_false while equals needs can_be_true.

The atom is now declined when the transform is measured to separate the constant's equality class: both spellings go through it in one column, compared with the index's own relation. Only a Dynamic, Variant or JSON member compares values across types, so a zero under such a member stands for a stored -0. in any spelling, a string that parses as one included, and is declined; a zero on a fixed-typed member beside it does not, nor does a constant denoting no number.

This covers =, != and isNotDistinctFrom; the IN set index reaches key space through tryPrepareSetIndexForIn and is untouched.

Measured cost, in granules: a zero constant on a separating transform stops pruning (1/125 to 125/125), as does a key whose image cannot hold -0. (2/65 to 65/65). ORDER BY (-f) keeps them equal and prunes as before; that ships as a test. LowCardinality(Float64) is not fixed here (#116637): the column collapses the two spellings on insert while the index does not.


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


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

`KeyCondition` can answer `f <op> const` over a transformed key by building a
range from the transform applied to the constant. `-0.` and `+0.` compare equal
but are distinct values, so a transform that reads the bit pattern maps them to
two different key values while the comparison feeding it treats them as one.
The point range built from one of them then misses the mark holding the other
and a matching row is dropped:

    CREATE TABLE t (f Float64) ENGINE = MergeTree ORDER BY toString(f)
    SETTINGS index_granularity = 1;
    INSERT INTO t VALUES (-0);
    SELECT count() FROM t WHERE f = 0;   -- 0, expected 1

Exactness is not the lever. `ORDER BY cityHash64(f)` is not injective, so that
atom is already relaxed, and it loses the row too: `relaxed` widens
`can_be_false`, while `equals` is `FUNCTION_IN_RANGE` and its `can_be_true` is
`intersects`, which nothing widens.

Decline the atom instead, in the caller and before the transform runs, so the
direct-CAST fast path inside `applyDeterministicDagToColumn` is covered by the
same check. The constant is read in the domain the comparison happens in
(`dag.input_type`), because that is the domain in which its equality class has
two members. `tryConvertFieldToType` rather than `convertFieldToType`: this path
already treats a constant it cannot apply as "no atom" rather than an error
(`WHERE p = 'not-a-uuid'` over `ORDER BY toUUID(p)`), and a throwing probe would
turn queries that work today into errors. A Null result needs no handling: the
transform's own conversion is accurate and rejects a cast introducing a NULL, so
it cannot have produced a zero from a constant that is not exactly a zero there.

The value is walked instead of testing the type for a float, because both `JSON`
and `Dynamic` are accepted as the argument of a transformed sorting key and
neither reports a float child, which would leave a silent hole exactly where the
consequence is silent wrong results.
…ellings

The previous commit declined the atom whenever the constant converted to a
floating-point zero in the key transform's input domain. That is more than
soundness needs, and it costs pruning where nothing was wrong: measured on 1000
rows with `index_granularity = 8`, `WHERE f = 0` over `ORDER BY (-f)`,
`ORDER BY (f * 2)` and `ORDER BY (f + 1)` all went `Granules: 1/125` to
`125/125`, while every one of those keys already returned the true count on an
all-negative-zero table. `-f` is the only way to write a descending
floating-point sort key, so the shape is idiomatic and the predicate is ordinary.

Decline only when the transform actually sends the two spellings to key values
the index does not compare as equal. Both spellings go through the transform in
one column, and the results are compared with `Range::equals`, which is the
relation the index itself uses (`accurateEquals`, plain `==` on two `Float64`,
so the zeros are equal there). `Field::operator==` is not usable for this: it
routes `Float64` through `FloatCompareHelper` and reports `NaN` equal to `NaN`.

The probe column is built in `dag.input_type` so that
`applyDeterministicDagToColumn` finds its input type already correct and
executes the same transform the index applied; entering with a plain `Float64`
column can instead take the direct-CAST fast path, which casts to the CAST's
result type without normalizing to the key's input type. The probe cannot
round-trip through the constant's own type either: for `WHERE f = 0` the
constant is a `UInt64`, `convertFieldToType(-0., UInt64)` is `0`, both probe
rows would become identical and the ordinary spelling would stay broken. A
non-floating-point input domain cannot hold the other spelling and its columns
need not accept a `Float64` value, so it is declined rather than probed.

A dynamically typed input domain (`Dynamic`, `Variant`, `Object`) is declined
before the constant is looked at, because there a value of one type equals a
value of another: a stored `Float64 -0.` equals a `0` written as a `UInt64`, so
the constant does not determine which values it stands for, and the converted
constant need not be a float at all. The test is recursive because a
`Tuple(Dynamic)` holding `(-0.)` loses a row the same way.

If the type comparison in `applyDeterministicDagToColumn` ever changes, the
probe's entry assumption is what breaks. No `try`/`catch` is added here: the
helper calls the declared `try` form of the shared converter, and
`applyDeterministicDagToColumn` owns the existing `catch`.
Five scenarios: `equals` and `notEquals` with the ordinary `WHERE f = 0`
spelling, a zero nested in a tuple constant, and two controls that must keep
pruning - a non-zero constant on a separating transform, and a zero constant on
`ORDER BY (-f)`, which sends both spellings to key values the index compares as
equal.
The changelog entry claims the sorting key, the partition key and a `minmax`
index, and the description claims `equals`, `notEquals` and `isNotDistinctFrom`
plus the decline on a dynamically typed input domain. The test pinned only
`ORDER BY` transforms with `equals` and `notEquals`, so four claimed surfaces
had no regression coverage even though every one of them is a measured carrier.

Four scenarios are added, each an all-negative-zero table read back with the
ordinary integer-spelled constant: `IS NOT DISTINCT FROM`, a
`PARTITION BY toString(f)` key, an explicit `INDEX ... toString(f) TYPE minmax`,
and a `Dynamic` column plus a `Tuple(Dynamic)` one.

The `Dynamic` constant is spelled `toUInt64(0)::Dynamic`: a bare `0` never
reaches key analysis against such a column, and the `UInt64` spelling is the one
a guard that looks at the constant instead of the domain misses, so it is what
makes the domain test load-bearing. The `Tuple(Dynamic)` scenario is what pins
the recursion through `forEachChild`; deleting that line leaves every other row
green.
…ive pruning control

Two gaps in the test, both found by measuring rather than by reading.

The `notEquals` row was setting-dependent. Its count can be answered from part
metadata by an implicit projection, and the metadata is exactly what the wrong
range describes, so with the projection path enabled the count returns 1 while a
read-and-filter returns 0. The runner randomizes that path off in about a tenth
of runs, and in 7 of 50 measured runs on a pristine binary the row therefore
agreed with its own ground truth and could not distinguish the defect. It now
carries a query-level clause pinning both projection settings to their defaults.
Pinning only the child is not enough: the test runner declares
`optimize_use_implicit_projections` as conditional on `optimize_use_projections`
and forces the child off whenever the parent is off, which was measured to defeat
a child-only pin. With both pinned, all eight carrier rows fail on a pristine
binary in every combination of the two settings, and 50 randomized runs produce a
single reddening set instead of two.

The `minmax` skip index had no control proving it still prunes. A scenario with a
non-zero constant is added whose plan row is the skip index's own granule count,
so the coverage cannot evaporate silently while the test still passes. It is
proven live, not constant: under a mutant that declines every atom on this path
the row disappears, because there is no granule line to extract when the index is
no longer consulted.

An equivalent control for the partition pruner is not included. The automatic
part-level min-max index on the partition key's column runs first and is handed
the same predicate, so it prunes every non-matching part by itself and the
partition pruner can only ever report one part out of one. The only pair of
`Float64` values a range comparison cannot separate is `-0.` and `+0.`, which is
the defect itself, so a non-zero fixture cannot attribute a strict reduction to
the partition pruner. The partition key keeps its carrier and ground-truth pair,
whose liveness two other mutants already establish.

No source change: `src/` is byte-identical to the previous commit.
Two pruning controls, each measured on both binaries and each held in place by a
named mutant rather than by assertion.

A non-zero constant on a `PARTITION BY toString(f)` key asserts that the
transformed atom still reaches the partition pruner. The assertion counts the
`Partition` section's own `Condition:` line naming `toString(f)` instead of
extracting its text, so a later change to how ranges are printed cannot fail the
test with a confusing diff. A `Parts:`-based control cannot work here: the
automatic part-level Min-Max index over the partition key's column runs first and
prunes every non-matching part by itself, so the `Partition` section can only
ever report `Parts: 1/1`. Proven live by the mutant that declines every constant,
under which the `Keys:`/`Condition:` pair collapses to `Condition: true`.

A non-zero constant inside a tuple asserts that a container constant holding no
zero still builds a pruning range. That is the accept direction of the container
branch, and replacing it with an unconditional decline leaves every previously
shipped row green, because declining is the safe direction and the tuple carrier
row cannot tell the difference. A new mutant does exactly that, and now moves
this row and nothing else.

Neither row can be answered from part metadata: the partition control's `EXPLAIN`
reads rows rather than counting them, and the tuple control's three rows live in
one part, so its predicate is never always-true for a part. Both rows are
byte-identical on the base and fix binaries in all four combinations of
`optimize_use_projections` and `optimize_use_implicit_projections`.

The comment above the `notEquals` row now names the always-true step that makes
that row depend on the projection settings.

No source change: `src/` is byte-identical to the previous commit.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 2, 2026
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Four rounds of independent review ran against this change before it was opened.
Each round was a cold read of the resulting code, done before reading the
implementation's own validation notes, plus a separate gate review. Nine
findings in round 1, seven in round 2, seven in round 3, and none in round 4
from either the cold read or the gate. Every one was adjudicated against the
code or against a measurement; the ones that changed the change, or that were
refused with evidence, are below.

# Finding Verdict
❌ The IN-set path pushes set elements through the same key transform and has no equality-class check, so a granule holding the other spelling can be pruned DISAGREE (measured). On this tree the two agree: f IN ('-0') prunes to 1 against a ground truth of 1, and f IN (0) on an all-negative-zero table prunes to 0 against a ground truth of 0 (ground truth = countIf over the whole table, no WHERE). The in set semantics separate -0. from +0. exactly as the transformed set index does, so no row is lost. The finding is conditional on #115970 landing, which is where that coupling belongs; noted below
⚠️ The ORDER BY (-f) control cannot detect an implementation that declines every scalar zero, because negate is taken by the monotonic branch first DISAGREE (measured, and by reading). That mutant was built and run: an unconditional return true immediately before the probe took this row from Granules: 1/3 to 3/3. It cannot be taken by the monotonic branch, because that branch's chain predicate requires is_always_monotonic or is_always_monotonic_where_defined, and negate reports only is_monotonic; the other monotonic branch cannot take it either, since the comparison's key-side argument is f while the only key column is negate(f)
❌ The test does not pin the partition-key, minmax, isNotDistinctFrom or dynamically typed behaviour that the changelog and description claim AGREE. All four are measured carriers, and the two dynamically typed ones are what the design's last two rounds were spent on, so they are the least safe to leave unpinned. Four scenarios added, each required to redden under a named mutant
❌ hasDynamicallyTypedComponent and its recursive walk had no regression coverage AGREE. Same fix as above: one row pins the integer-spelled constant in a Dynamic domain (the spelling a check on the constant's own shape misses), one pins the recursion through Tuple(Dynamic)
❌ The != regression row stops distinguishing the fix from the bug when a randomized setting turns off the channel that answers a count() without reading rows AGREE. Measured on the base build: that row reads 1 with implicit projections on and 0, equal to its own ground truth, with them off, so it was live in only about 95% of runs. Every row's base-arm behaviour was then re-measured across both settings that can answer such a count, and the affected row pins both at their own defaults. The proposed second setting was the wrong one: the dependence is on the parent optimize_use_projections, which the runner uses to force the child off, so a child-only pin is defeated
❌ The partition-key and minmax rows would also pass if partition pruning or the skip index stopped running at all, so their coverage could disappear silently AGREE, with a different remedy than proposed. A plan assertion on the declined case is not the fix: a declined atom reads Parts: 1/1 with no Skip section, which is also what a pruner that no longer runs reads. Each scenario now ships a paired control with a non-zero constant, where pruning legitimately still happens and the plan row shows it
❌ The dynamically typed cases cover only Dynamic with a zero, so the Variant and JSON members of the same check, and the fact that the decline ignores the constant, are unpinned DISAGREE on the remedy, facts agreed. The proposed rows would pass under the very mutants they are meant to kill: convertFieldToType returns a Float64 field unchanged for a Variant that contains Float64, and the guard then declines because a Variant is not a floating-point domain, so such a row is green with or without the Variant member; the JSON member is shadowed the same way by the value walk over an object field. And the constant-ignoring behaviour is already pinned: the shipped Dynamic row spells its constant as an integer, which converts to a non-float value, so restricting the decline to a zero-valued constant reddens it
⚠️ JSON was listed as a non-carrier in the validation notes while the gate treated it as one AGREE, and resolved against my own record. JSON is a carrier in three of five spellings, and re-probing its neighbour found Map(String, Float64) is one too. Both earlier "control" measurements had used a spelling that never armed the predicate. The notes are corrected; the description already covered both, because the dynamically typed domains are declined for every constant
❌ The partition scenario still has no assertion that the transformed atom reaches the partition pruner at all AGREE. Adopted in the form the implementation measured, with three changes: count the Partition section's own Condition: line naming toString(f) rather than extracting its text, so a change to how ranges are printed cannot fail the test with a confusing diff; read rows rather than counting them, so no projection can answer the EXPLAIN; and drop the redundant ground-truth row. Proven live by the mutant that declines every constant, under which the whole Keys:/Condition: pair collapses to Condition: true
⚠️ Make that control assert a strict Parts: reduction instead DISAGREE (structural, and measured). Two independent reasons. The automatic part-level Min-Max index over the partition key's required column runs before the Partition pruner and is handed the same predicate, so with one distinct value per partition it prunes every non-matching part itself and the Partition section can only ever report Parts: 1/1. And the only Float64 pair a range comparison cannot separate is {-0., +0.}, which is the carrier itself, so no non-zero fixture can ever attribute a strict Parts: reduction to the partition pruner. Predicted in writing, then confirmed: the mutant moves none of those rows
❌ The container branch's accept direction is undetectable: replacing its value test with an unconditional decline leaves every shipped row green AGREE. Declining is the safe direction, so the tuple carrier row returns the correct answer either way and cannot see it. A non-zero tuple control was added, and a new mutant that declines every container constant now moves that row and nothing else in the suite
⚠️ Add non-zero plan assertions for notEquals and isNotDistinctFrom too DISAGREE. The mutant they target is not a mutant of this change: the operator list is pre-existing, the guard is its sole call site in src/, and the guard takes no operator argument, so the two scalar equals controls already pin it for all three operators. Adding them would pin pre-existing notIn-range pruning that this change does not touch
⚠️ The description claimed IN was "a different layer (#115970)" AGREE. Both halves were wrong: IN reaches key space through the same transform in the same file, and #115970 touches no file in this directory. Rewritten as a scoping sentence that asserts no defect
⚠️ The dynamically typed decline applies to every constant, not only a zero, and the description did not say so AGREE. Stated explicitly now, since it withdraws pruning from a transformed key over Dynamic, Variant or JSON for any predicate
💡 When tryConvertFieldToType cannot convert the constant into the transform's input type it returns an empty value, which the guard reads as "safe" while its two neighbouring failure paths decline DISAGREE on the remedy, fact agreed. No input reaching a zero through that branch could be constructed: a zero converts exactly into every float type, container conversion is all-or-nothing, and every wrapper target is handled. Left alone rather than adding a guard for a path that cannot be exercised
💡 fieldHoldsFloatZero's comment justifies the iterative walk instead of stating an invariant DISAGREE. It is neither obvious from the code below it nor a reference to this fix, and deep value nesting is a hazard the surrounding code already guards against
💡 The description was over the length budget AGREE, condensed
💡 Two pieces of accompanying text had gone stale against the shipped test AGREE, both corrected: a scenario count that no longer matched the file, and a comment that named the setting a row pins without naming the step that makes the row depend on it

Round 4 changed nothing. The delta was verified by reading rather than by
trusting the report, and two of its expected values were re-derived from the
sources instead of from the measurement: the partition control matches exactly
one plan line because the part-level Min-Max index is built over the
partition expression's required columns, so its condition is over the raw
column and cannot contain toString(f); and the tuple control's 2/3 follows
from a granule's right bound being the next mark. The one new expression
assertion was checked against 118 existing reference files that pin
Condition: lines, which print function keys unqualified under the current
analyzer. The runner has no occurrence of use_partition_pruning,
use_skip_indexes or use_primary_key, so no plan assertion here is exposed
to a randomized pruning switch.

Two things worth flagging. For whoever lands #115970: making IN agree with
equals on negative zero also makes the transformed IN-set index in
KeyCondition inconsistent, because it separates the two spellings the same way
the comparison atom did. That path is untouched here and is consistent today, so
this is a heads-up rather than a defect report. And the Variant and JSON
arms of the domain check are fail-closed members with no test row of their own:
both are also declined further down, for not being a floating-point domain, so
no oracle can isolate them. The Variant carrier is measured in this PR's
validation rather than pinned.

The LowCardinality(Float64) shape is likewise untouched: such a column
collapses the two spellings on insert while the index does not, which is #116637.

Session id: cron:clickhouse-review-self-slot-58:20260902-022500

@clickhouse-gh clickhouse-gh Bot closed this Sep 2, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8278b1c]

Summary: ❌

job_name test_name status info comment
LLVM Coverage FAIL
Generate LLVM Coverage Diff Report FAIL cidb
Print Uncovered Code FAIL cidb Uncovered code analysis did not run: bash ci/jobs/scripts/generate_diff_coverage_report.sh failed (its output is on the Generate LLVM Coverage Diff Report result).
Parser memory check ERROR
Resolve master binary ERROR

AI Review

Summary

This PR teaches KeyCondition to stop pushing a zero constant through transformed keys when -0. and +0. can map to different key values, and the new regression file covers the main Float64 / Dynamic / JSON carriers. One gap remains: Variant is treated as a cross-type "dynamic domain" unconditionally, so under use_variant_default_implementation_for_comparisons = 0 the new guard now disables valid pruning for exact transformed Variant keys.

Findings
  • ⚠️ Majors
    • [src/Storages/MergeTree/KeyCondition.cpp:2387-2528] isDynamicallyTypedDomain always classifies Variant like Dynamic / JSON, and keyTransformCanSeparateEqualValues therefore declines any zero-like Variant constant even when use_variant_default_implementation_for_comparisons = 0 switches = / != / isNotDistinctFrom back to native Variant semantics. With that supported setting, WHERE v = toUInt64(0)::Variant(Float64, UInt64) no longer matches a stored Float64(-0.), so a transformed key such as ORDER BY toString(v) should keep its exact point range instead of falling back to a full scan.
      Suggested fix: thread the session setting into this check (or cache a boolean on KeyCondition) so only Dynamic / JSON stay in the widened "any spelling of zero" path unconditionally; Variant should use that path only when the default comparison implementation is enabled. Add a focused regression with SET use_variant_default_implementation_for_comparisons = 0 to pin the accept-direction behavior.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Respect use_variant_default_implementation_for_comparisons in the new Variant branch of keyTransformCanSeparateEqualValues.
    • Add a regression proving transformed Variant keys still prune under use_variant_default_implementation_for_comparisons = 0.

LLVM Coverage Report

⚠️ No coverage measurement for commit 8278b1c: bash ci/jobs/scripts/generate_diff_coverage_report.sh failed (its output is on the Generate LLVM Coverage Diff Report result).

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, three statements: CREATE TABLE t (f Float64) ENGINE = MergeTree ORDER BY toString(f) SETTINGS index_granularity = 1; INSERT INTO t VALUES (-0); SELECT count() FROM t WHERE f = 0; returns 0 against a ground truth of 1. The reporter's own repro in #117543 reproduces byte-for-byte on the base binary (count() 1, Granules: 2/4).
b Root cause explained? Yes. Key analysis answers f <op> const over a transformed key by applying the transform to the single constant and using the result as a range bound. -0. and +0. compare equal under floating-point equality but are distinct values, so a transform that reads the bit pattern maps them to two different key values; the point range built from one does not intersect the mark holding the other, and a matching row is never read. The atom is a strict subset of the predicate.
c Fix matches root cause? Yes. The atom is declined exactly when the transform is measured to separate the constant's equality class, so no range is narrower than the predicate it stands for. Exactness is not the lever, and that is measured rather than argued: ORDER BY cityHash64(f) is already non-injective, hence already relaxed, and still loses the row, because relaxed widens only can_be_false while equals is FUNCTION_IN_RANGE whose can_be_true is intersects.
d Test intent preserved / new tests added? New test 05055_key_condition_signed_zero_constant: 12 tables and 28 reference rows, covering eight wrong-result scenarios and five pruning controls. The eight: equals, notEquals and IS NOT DISTINCT FROM with the ordinary WHERE f = 0 spelling; a zero nested in a tuple constant; a PARTITION BY toString(f) key; an explicit INDEX ... toString(f) TYPE minmax; a Dynamic column and a Tuple(Dynamic) one. The five controls each assert that pruning is preserved for a constant this change must not decline: a non-zero constant on the primary key, a zero constant on ORDER BY (-f) (a transform that keeps both spellings equal), a non-zero constant inside a tuple, a non-zero constant on a partition key (asserting the transformed atom still reaches the partition pruner), and a non-zero constant against the minmax skip index. Every wrong-result row is paired with a countIf ground-truth row in the same reference. No existing test was modified, weakened or removed, and no existing reference moved.
e Both directions demonstrated? Yes, on Build-ID-asserted base and fix binaries: for the shipped test (8 of its 28 rows redden on base in every combination of the two projection settings, and the 5 plan-assertion control rows are byte-identical on both arms, as are the two new controls' full EXPLAIN plans line for line), for 20 carrier shapes, for the issue's literal repro (1 to 2, Granules: 2/4 to 4/4) and for the container-key case added to that issue afterwards (1 to 2, Granules: 2/4 to 4/4, with an in-range control that keeps pruning 2/4 on both arms). Eight mutation arms, each with its reddening set predicted in writing before the run and matched exactly after, each built to its own distinct Build ID: arm 4 reddens only the ORDER BY (-f) control, arm 7 only the Tuple(Dynamic) row, arm 8 only the non-zero-tuple granule count, and arm 5 (decline everything) is the only arm that touches the partition-pruner control. Every control is therefore held in place by a named mutant rather than by assertion.
f Fix is general across code paths? One guard in the single caller of the only function on this path (the equals/notEquals/isNotDistinctFrom branch), placed so it covers both entry points: the transform-DAG path and the direct-CAST fast path inside applyDeterministicDagToColumn, both measured. Consumers verified beyond the primary key, and each pinned by its own test scenario: PARTITION BY and an explicit minmax skip index. The IN-set path is deliberately untouched: measured, IN genuinely does not match -0. today, so index and row level agree there, which is #115970's layer.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured across Float64, Float32, BFloat16, Nullable(Float64), Tuple(Float64, Float64), Array(Float64), Map(String, Float64), Dynamic, Tuple(Dynamic), Variant, JSON and LowCardinality(Float64); constant spellings '-0', -0., 0, toFloat64('-0'), ::Dynamic, ::Variant, tuple(0); transforms toString, CAST AS String, toFixedString, reinterpretAsUInt64, cityHash64, reinterpretAsUInt64(f) + 0.5, negate, f * 2, f + 1. Non-float domains (Int64, Decimal64, String) confirmed byte-identical. Field has no Float32, so Float32 and BFloat16 constants arrive as Float64 and are covered by construction.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no serialization format and no default is changed, so no SettingsChangesHistory.cpp entry is needed. The change only makes pruning more conservative, so it cannot reject input that is accepted today and needs no gate. The two pruning withdrawals are intended, bounded and disclosed with their measured numbers in the description.
i Invariants and contracts preserved? The invariant is that a key or index range built from a constant must not exclude a key value a row satisfying the predicate can carry; declining the atom is the fail-closed side of it. out_value and out_type still hold the original constant at the guard's position, which the probe requires. The caller returns immediately on a false result and reads the exactness out-parameter only on the true path, so the guard's position below that assignment has no observable effect, and every control row is byte-identical. Range::equals is the index's own relation (accurateEquals, plain == on two Float64); Field::operator== was rejected because it reports NaN equal to NaN. No try/catch is added: the helper calls the declared try form of the shared converter and applyDeterministicDagToColumn owns the existing catch.

Regression sweep: 139 tests (*key_condition*, *partition_pruning* and a fixed 50-test neighbour batch), a fresh server per arm, --no-random-settings --no-random-merge-tree-settings. The two failure sets differ by exactly one entry, this PR's own new test, which fails on the base binary. That sweep is not repeated for test-only rounds, because src/ is byte-identical to the tree it swept.

50 randomized runs of the final 28-row test twice, once alone and once under a concurrent 50-test neighbour batch at --jobs 8: 50 OK / 0 FAIL both times. Randomization confirmed live from system.query_log rather than assumed: 15486 QueryFinish rows carrying 201 distinct max_block_size, 5 max_threads, 7 session_timezone and 462 distinct settings signatures, with parallel replicas exercised in 3116 of them. The pinned notEquals row logged optimize_use_projections = 1, optimize_use_implicit_projections = 1 in all 170 of its rows while the unpinned ground-truth row was injected (0,0) or (unset,0) in 22 of its own - the query-level clause beating runner injection, observed rather than argued. On the base binary the 8 wrong-result rows redden in all four combinations of those two settings, and in a 50-run randomized sweep of the previous revision, 50 times out of 50 with a single reddening set.

Session id: cron:clickhouse-impl-self-slot-57:20260902-004700

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @shankar-iyer, could you review this? Key analysis pushes the comparison constant through the key transform and uses the result as a range, but -0. and +0. compare equal while toString maps them to two different key values, so the point range built from one spelling dropped the mark holding the other and a matching row was silently lost. The atom is now declined only when the transform is measured to separate the constant's equality class, so a key like ORDER BY (-f) keeps pruning as before.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
A `Variant` domain compares values of different alternatives as equal, and a
constant there can sit on the integer alternative, so the constant carries no
floating-point value at all while still standing for a stored `-0.`. Only the
test on the domain catches that: the walk over the constant's own value sees an
integer and accepts the atom.

That member had no row of its own. Deleting `Variant` from the domain test left
every shipped row green while `WHERE v = toUInt64(0)::Variant(Float64, UInt64)`
went back to dropping the mark holding `-0.` on a `Variant(Float64, UInt64)`
key, measured on both binaries. The new scenario is the missing pin: a mutant
that deletes exactly that member now moves this row and nothing else, while the
mutant that deletes `Dynamic` moves the two `Dynamic` rows and leaves it green.

`JSON` cannot be pinned the same way. Every `JSON` constant measured here that a
stored `-0.` compares equal to carries a floating-point zero inside it, so the
walk over the constant's value declines it before the domain is consulted, and
the one spelling whose value holds no float, `'{"a":0}'::JSON`, does not compare
equal to a stored `-0.` at all.

No source change: `src/` is byte-identical to the previous commit.
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8278b1c79 with master bb3c0a852 (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

4 object files changed (+35.04 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/KeyCondition.cpp.o 1.42 MiB 1.45 MiB +35.02 KiB (+2.42%)

716 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

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

Median compile-time ratio to the baselines is ×0.91 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -0.1 s (-1%) in total before that adjustment.

Job report

…note a zero

The screen declined every constant whose key transform reads a dynamically typed
column. That withdrew pruning an existing test asserts: over
ORDER BY (json.a, json.b::String), the atom json.b = 'str_0' lost
CAST(json.b, 'String') from the condition and read 2/8 granules instead of 1/8,
in 03277_json_subcolumns_in_primary_key.

Such a domain compares values across types, so a stored -0. equals a zero
written as an integer, as a decimal, or as a string that parses as one, and each
of those spellings still has to be declined. A constant that denotes no number
stands for itself alone there, so the range built from it is sound and is kept.

The two new test rows pin both directions: a zero written as a string is still
declined, and a constant denoting no number keeps Granules: 1/3.
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI caught an over-decline in the guard; narrowed in c9c6301e40ac7f857dda87d2c8ffb35d52ff90fa

03277_json_subcolumns_in_primary_key failed on the previous head across five check configurations. The
guard declined every constant whose key transform reads a dynamically typed column, so over
ORDER BY (json.a, json.b::String) the atom json.b = 'str_0' lost CAST(json.b, 'String') from the
condition and read 2/8 granules where that test's shipped reference asserts 1/8. Results stayed
correct, which is why only the plan pin caught it. I reproduced it on both binaries before touching
anything, and I did not consider editing that reference: the pruning it asserts is the contract.

The decline is now conditioned on the constant. Such a domain compares values across types, so a zero
written in another numeric type, or as a string that parses as one, still stands for a stored -0. and is
still declined; a constant that denotes no number stands for itself alone there, so its range is kept.
03277 passes, and all ten carrier shapes on a dynamically typed domain stay fixed, including
Dynamic, Tuple(Dynamic), Variant, three JSON spellings and Map(String, Float64).

Two new reference rows pin both directions, each with a mutant that kills it and nothing else: reverting
the narrowing moves the accept-direction row from Granules: 1/3 to 3/3, and refusing a string in the
zero test moves the carrier row alone. Ten of the 35 rows redden on a pristine master binary. 50
randomized runs alone and 50 at --jobs 8 pass.

One residual, disclosed rather than fixed here: a transform that reads the stored type instead of the
value separates values of different types that compare equal, so ORDER BY dynamicType(d) with
WHERE d = toUInt64(1)::Dynamic over a stored Float64(1.) returns 0 rows against a full-scan answer of

  1. That reproduces identically on master, it is cross-type identity rather than the signed-zero identity
    this PR fixes, and no value-level probe can be sound for it.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Outdated
auto check = [&](const IDataType & child)
{
const WhichDataType which(child);
result = result || which.isDynamic() || which.isVariant() || which.isObject();

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.

Variant is not unconditionally a "dynamic-domain" comparison here. With use_variant_default_implementation_for_comparisons = 0, the comparison functions bypass the default Variant adaptor and fall back to native Variant semantics, where UInt64(0)::Variant(Float64, UInt64) no longer matches a stored Float64(-0.) just because the numeric values are equal.

This branch still declines the atom for every zero-like Variant constant, so a transformed key such as ORDER BY toString(v) (or any other exact transform over v) loses valid pruning under that supported setting. KeyCondition needs the same setting split that the comparison path already has, and it needs a regression with use_variant_default_implementation_for_comparisons = 0.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
…the two zeros

`keyTransformCanSeparateEqualValues` tested two things independently: whether the
key expression's input type contained a dynamically typed member anywhere, and
whether the constant held a zero anywhere. So a zero sitting under a fixed-typed
member of a mixed container tripped the widened "any spelling of a zero" rule that
only a dynamically typed member needs.

`Tuple(UInt64, Dynamic)` with the constant `(0, 1)` is the smallest case. The zero
is on the `UInt64` member, which has a single spelling of zero and cannot hold a
stored `-0.`, so the atom was exact; it was declined anyway and the key stopped
pruning altogether, measured as `Granules: 1/5` becoming `5/5`.

Walk the constant together with its type and choose the leaf test per member: any
spelling of a zero under a dynamically typed member, only a `Float64` zero
elsewhere. A value that does not have the shape of its own type cannot be read, so
it is declined.

Two rows pin both directions. A zero on the dynamic member of a mixed container
still declines, which also pins the positional pairing between elements and element
types; a zero on the fixed-typed member beside it keeps its granule count.
`Build (arm_tidy)` runs clang-tidy with `-warnings-as-errors`, and
`readability-container-data-pointer` rejects `&entry_elements[0]`. The value
member is spelled the same way so the key and the value read alike. No
behaviour change: the `Map` entry is checked to be a two-element tuple
immediately above.
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8278b1c

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
Parser memory check / Resolve master binary master-side, not this diff: praktika's static S3 prefix gained an unconditional workflow-name segment in #110081, so this job's hand-spelled baseline key REFs/master/<sha>/build_arm_release/clickhouse-examples 403s on every tracked commit and the step errors No master clickhouse-examples artifact was found. 152 distinct pull requests carry it since 2026-09-02 10:14:18Z, 0 true-master runs #117701 (mine, merged 2026-09-02T16:49:23Z). This tree predates the merge, so the red is expected here; the master merge that picks it up is deferred to avoid a rebuild that cannot turn the head green yet
LLVM Coverage / Generate LLVM Coverage Diff Report, then Print Uncovered Code as its cascade master-side, not this diff: the same #110081 prefix change orphaned the hand-spelled coverage baseline key, so the 100-commit baseline walk finds nothing and the uncovered-code step never runs. 58 distinct pull requests carry it since 2026-09-02 13:07:52Z, 0 true-master runs #117718 (external, open)

Session id: cron:our-pr-ci-monitor:20260902-193000

@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 added a commit that referenced this pull request Sep 9, 2026
…elling of a zero

`IN` on a floating point column now matches a stored `-0.` against a set that contains `0.`, but
`tryPrepareSetColumnsForIndex` pushed each set element through the sorting key transform as written.
With a key like `ORDER BY reinterpretAsUInt64(f)` the element `0.` becomes the key value `0` while the
stored `-0.` lives at `0x8000000000000000`, so `MergeTreeSetIndex::checkInRange` could report
`can_be_true = false` and prune away a granule that row evaluation matches. The transform is injective
there, so `out.relaxed` is not set and nothing masked the over-pruning.

Decline the set index for such a transform: when the set holds a floating point zero at any depth and
the key transform sends `-0.` and `0.` to key values the index compares as unequal, the atom is left to
row evaluation. The screen looks at the elements that are actually in the set, so pruning is kept when
the set has no zero in it, and it is value-independent on a domain whose type is only known at runtime,
where one pair of probes cannot decide the whole value.

The same composition on the `equals` / `notEquals` / `isNotDistinctFrom` atoms is fixed separately in
#117611.

Co-Authored-By: Claude Opus 5 (1M context) <[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 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... groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

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

1 participant