Skip to content

Do not move conditions over float sorting key columns to PREWHERE under FINAL - #122142

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/no-prewhere-over-float-sorting-key-under-final
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/no-prewhere-over-float-sorting-key-under-final

Conversation

@groeneai

@groeneai groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121782
Related: #121350

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 wrong results from SELECT ... FINAL with optimize_move_to_prewhere_if_final enabled when a condition is over a floating-point sorting key column. -0.0 and 0.0 are one key for the FINAL merge, as are all NaN payloads, so a condition such as toString(f) = '0' was evaluated per part before the merge, discarded the winning row version and returned a superseded row. Conditions over sorting key columns whose type is or contains a floating-point type are no longer moved to PREWHERE under FINAL.

Description

On 26.8-lts and 26.9-stable, a SELECT ... FINAL over a Float64 sorting key returns the superseded row (1, 0, 1) instead of the empty result:

CREATE TABLE t (id UInt64, f Float64, v UInt64, s String)
ENGINE = ReplacingMergeTree(v) ORDER BY (id, f);
INSERT INTO t VALUES (1, 0.0, 1, 'stale');
INSERT INTO t VALUES (1, -0.0, 2, 'winner');
SELECT * FROM t FINAL WHERE toString(f) = '0'
    SETTINGS optimize_move_to_prewhere_if_final = 1;   -- 1  0  1  stale, correct answer is empty

#121782 fixed the row policy half; this is the follow-up for the PREWHERE half, which needs no policy at all.

Root cause: a conjunct may move to PREWHERE under FINAL if it is deterministic over the sorting key, which would give one verdict per deduplication group. True for value identity, but the FINAL comparator is coarser for floats: toString separates what it merges.

Change: MergeTreeWhereOptimizer excludes float-containing sorting key columns from the set that authorises the move. One site, both entry points, fewer conditions moved and only under FINAL.

That guard is already written in open #121350, and I kept this copy character-identical to it, so whichever lands first the other side is a rename and a dropped hunk; both edit the same Settings.cpp block as well. It is separate because it flips no default and adds no settings-history entry, so it backports to the releases where the wrong result is live, and because its test adds the NaN, Nullable(Float64), Tuple and doubly nested cases on the PREWHERE side, which today exist only for the row policy path (05241). Happy to close it and fold everything into #121350 instead, your call.

Validation: 6 defect cases red without the fix and green with it, 5 positive controls green in both arms, 100/100 randomized, 14 neighbouring tests unchanged.


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

…er FINAL

A SELECT ... FINAL with optimize_move_to_prewhere_if_final = 1 and a condition
over a floating-point sorting key column returned a superseded row instead of
the correct answer:

    CREATE TABLE t (id UInt64, f Float64, v UInt64, s String)
    ENGINE = ReplacingMergeTree(v) ORDER BY (id, f);
    INSERT INTO t VALUES (1, 0.0, 1, 'stale');
    INSERT INTO t VALUES (1, -0.0, 2, 'winner');
    SELECT * FROM t FINAL WHERE toString(f) = '0'
        SETTINGS optimize_move_to_prewhere_if_final = 1;

returned (1, 0, 1, 'stale') where the correct answer is empty.

MergeTreeWhereOptimizer admits a conjunct to PREWHERE under FINAL when it is
deterministic over the sorting key, on the reasoning that such a filter gives
the same verdict for every row of one deduplication group and so cannot change
which row wins the merge. That reasoning holds for value identity, but the FINAL
merge comparator is coarser than value identity for floating point: -0.0
compares equal to 0.0 and every NaN bit pattern compares equal to every other,
while toString() and reinterpretAsUInt64() separate exactly those values. The
moved condition was therefore evaluated per part before the merge, dropped the
group's winner, and left the superseded row to survive a merge it should have
lost.

Exclude sorting key columns whose type is or contains a floating-point type from
the set that authorises the move. One initializer covers both optimizer entry
points, since the AST and ActionsDAG overloads read the same member, and all
three readers of that set are gated on the query being FINAL. The change
therefore makes the optimizer strictly more conservative and only for FINAL:
fewer conjuncts move, never more. Because the direction is "move less" it cannot
reintroduce the NOT_FOUND_COLUMN_IN_BLOCK regressions of ClickHouse#111709, ClickHouse#111721 and
ClickHouse#111940, which came from a moved prewhere column going missing.

The helper mirrors sortingKeyNamesSafeBeforeFinal, which ClickHouse#121782 added to
ReadFromMergeTree for the row policy half of the same defect, so the two halves
read as one mechanism. It stays file-local because the three call sites of the
float predicate take three different inputs, and because keeping it local leaves
this change backportable: no setting default moves and no SettingsChangesHistory
entry is owed.

The new test covers Float64, NaN payloads, Nullable(Float64), Tuple(Float64,
UInt8) and Array(Tuple(Float64, UInt8)), since IDataType::forEachChild is
recursive and the top level is unwrapped. Each of those cases was measured to
fail without this change. It also carries positive controls that must not move:
a non-float column of the same mixed sorting key still reaches PREWHERE, an
all-integer sorting key is untouched, and the path with the setting disabled is
unchanged. The fixture keeps one row per INSERT and stops merges, because a
fixture that collapses to a single part makes every assertion pass even on an
unpatched build.

Related: ClickHouse#121782
Related: ClickHouse#121350

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold
review of the resulting tree, done before reading the implementation evidence.

# Sev Finding Verdict Evidence / action
1 - Independent model pass over MergeTreeWhereOptimizer and its header, both caller paths, the matching ReadFromMergeTree guards, the recursive type-wrapper implementations, the setting declaration and the new test 0 findings nothing to adjudicate
2 ⚠️ My own review: the description understated the overlap with #121350 and gave a reason for the duplicated predicate that does not hold (it claimed the copies take different input types; two of the three take a KeyDescription) AGREE corrected before publishing: the description now says outright that the guard is character-identical to #121350's, that both PRs edit the same Settings.cpp block, and that either can land first
3 ⚠️ My own review: the description claimed the NaN, Nullable(Float64) and Tuple cases exist nowhere yet. 05241, added by #121782, already has all three AGREE corrected before publishing: the claim is now scoped to the PREWHERE path
4 💡 Only the first table carries the two-parts-are-stored guards, so the "superseded version does not come back" assertions on the other five tables would also be empty if a fixture ever collapsed AGREE, noted not blocking each of those sections also asserts the fixture-independent PREWHERE filter count (measured 2 without the fix, 0 with it), and SYSTEM STOP MERGES plus one row per INSERT close the known collapse paths

Two things I checked independently rather than taking from the implementation notes.

The narrowed set cannot affect a non-FINAL query: all three readers of sorting_key_names are
gated on is_final, and at the cannotBeMoved site the narrowing pushes the answer towards "do
not move". The type walk has no reachable hole either, because everything else that could hide a
float is refused as a key outright: Variant, Dynamic and JSON by KeyDescription, and
AggregateFunction by the isComparable check. Decimal has no negative zero and is correctly
left in, and the geo types are tuples and arrays, so the recursive walk sees their floats.

On whether this is one site out of several: the sibling carriers of the same invariant are already
guarded, including one the implementation notes did not list. PartsSplitter::isSafePrimaryDataKeyType
already rejects floats recursively and the lazy FINAL split gates on it, so for ORDER BY (id, f)
that path bails out, and for ORDER BY (id, f) PRIMARY KEY id the two versions share a primary key
range and still reach the merge. After this PR I could not find an unguarded carrier left.

Severity: ❌ blocker / ⚠️ major / 💡 nit. Findings on hunks unchanged by a fix round are auto-dropped.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, not a rate. The reproducer in the description returns 1 0 1 stale on every run of an unpatched Debug build, and the empty result on every run of the patched one.
b Root cause explained? Yes. A conjunct is admitted to PREWHERE under FINAL when it is deterministic over the sorting key, on the reasoning that it then gives one verdict for a whole deduplication group. That reasoning holds for value identity, but the FINAL comparator is coarser than value identity for floats (-0.0 equals 0.0, every NaN payload equals every other), while toString and reinterpretAsUInt64 separate exactly those values. The moved condition is evaluated per part before the merge, drops the group's winner, and the superseded row survives.
c Fix matches root cause? Yes. It removes from the authorising set precisely the columns whose comparator is coarser than value identity. No widened bound, no no-random-* tag, no reduced dataset, and no guard at the symptom site.
d Test intent preserved / new tests added? New stateless test with 6 defect cases and 5 positive controls. No existing test weakened: 14 neighbouring prewhere/FINAL tests pass unchanged. The fixture deliberately keeps two parts, because a fixture that collapses to one was measured to make every assertion pass on unpatched master.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Without the fix the new test diffs in 5 mechanism assertions and 5 result rows; with the fix the diff is empty.
f Fix is general across code paths? Yes, and one site is the whole fix: both optimizer entry points (the AST and the ActionsDAG overload) read the same member. The four sibling carriers of this invariant in ReadFromMergeTree and KeyCondition are already guarded, so this was the last unguarded one. Fixed at the source, not at the point of the wrong answer.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, and asserted: Float64, NaN payloads, Nullable(Float64) with allow_nullable_key = 1, Tuple(Float64, UInt8), and Array(Tuple(Float64, UInt8)) at nesting depth 2. IDataType::forEachChild is fully recursive and the top level is unwrapped, so LowCardinality, Map and Variant nestings fall out of the same predicate. Decimal is integer-backed with no distinct negative zero and is correctly not excluded. The same optimizer and merge serve Replacing, Collapsing, VersionedCollapsing, Summing, Aggregating and Coalescing.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. No setting default and no serialization changed, so no SettingsChangesHistory.cpp entry is owed and no existing data needs migration. A user who opted into optimize_move_to_prewhere_if_final sees fewer PREWHERE moves for float-keyed tables under FINAL, which is now stated in that setting's own documented description.
i Invariants and contracts preserved? Yes. The invariant is that a filter may run before the FINAL merge only if it cannot distinguish two rows the comparator treats as one key. The narrowed set only ever grants permission, and all three of its readers are gated on the query being FINAL, so the optimizer becomes strictly more conservative and only there: fewer conjuncts move, never more. Because the direction is "move less", it cannot reintroduce the NOT_FOUND_COLUMN_IN_BLOCK family (#111709, #111721, #111940), which came from a moved prewhere column going missing. Non-FINAL plans and optimize_move_to_prewhere_if_final = 0 are unchanged.

Session id: cron:clickhouse-impl-slot-7:20260925-015700

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c85e6e2]


AI Review

Summary

This PR narrows optimize_move_to_prewhere_if_final so auto-moved predicates over float-containing sorting-key columns no longer run before FINAL, which fixes the specific WHERE -> PREWHERE wrong-result path described in the PR. I do not think the fix is complete yet, because the same predicate still appears reachable through an explicit PREWHERE, so the underlying correctness invariant is still bypassable.

Findings

❌ Blockers

  • src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:152 The new sorting_key_names filter only affects predicates that arrive through MergeTreeWhereOptimizer, i.e. conditions auto-moved from WHERE. An explicit PREWHERE on the same float sorting key still runs before FINAL, because ReadFromMergeTree::isPrewhereDeferredAfterFinal only checks apply_prewhere_after_final and deferred row policy, not whether the existing prewhere_info predicate can distinguish rows inside one deduplication group. That leaves the same wrong-result reachable as SELECT ... FINAL PREWHERE toString(f) = '0' on ORDER BY (id, f), where the winning -0.0 / NaN row can still be filtered out before merge.
    Suggested fix: apply the same float-key safety check to the existing PREWHERE entrypoint in ReadFromMergeTree, deferring or rejecting unsafe PREWHERE filters under FINAL instead of only preventing new ones from being synthesized.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: close the remaining explicit-PREWHERE path, or otherwise prove that it cannot hit the same wrong-result scenario under FINAL.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 25, 2026
@yakov-olkhovskiy yakov-olkhovskiy self-assigned this Sep 25, 2026
, supported_columns_include_subcolumns{supported_columns_include_subcolumns_}
, sorting_key_names{NameSet(
storage_snapshot->metadata->getSortingKey().column_names.begin(), storage_snapshot->metadata->getSortingKey().column_names.end())}
, sorting_key_names{sortingKeyNamesSafeBeforeFinal(storage_snapshot->metadata->getSortingKey())}

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.

This only closes the WHERE -> PREWHERE optimizer path. A user-written PREWHERE on the same float sorting key still runs before FINAL, because ReadFromMergeTree::isPrewhereDeferredAfterFinal only checks apply_prewhere_after_final / deferred row policy and never inspects query_info.prewhere_info itself (src/Processors/QueryPlan/ReadFromMergeTree.cpp:3193).

That means the same wrong result is still reachable as:

SELECT * FROM t FINAL PREWHERE toString(f) = '0'

on ORDER BY (id, f), where the PREWHERE can discard the winning -0.0 / NaN row before the FINAL merge and leave the superseded row behind. If the invariant is "predicates that can distinguish rows inside one FINAL deduplication group must not run before FINAL", the existing PREWHERE entrypoint needs the same guard or deferral as the auto-move path.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 25, 2026
@yakov-olkhovskiy

Copy link
Copy Markdown
Member

closing in favor of #121350

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, folding into #121350 is right: its MergeTreeWhereOptimizer hunk and mine are functionally identical, so my src change adds nothing #121350 does not already do.

One thing that dies with this PR, if it is worth keeping. #121350's new block in 04500_prewhere_final_nondeterministic_condition.sql covers plain Float64 only. 05257_prewhere_after_final_float_sorting_key.sql here also covers NaN payloads, Nullable(Float64), Tuple(Float64, UInt8) and Array(Tuple(Float64, UInt8)), plus positive controls that an integer sorting key and the non-float column of a mixed key still move. Those are the same carriers you asked for on the row policy side of #121782. The file is on this PR's branch and can be picked into #121350 as is, or I can send it as a test-only PR. Dropping it is fine too.

Separately, one measurement from validating the guard: an explicit PREWHERE is not covered by either change.

CREATE TABLE t (id UInt64, f Float64, v UInt64, s String) ENGINE = ReplacingMergeTree(v)
ORDER BY (id, f) SETTINGS max_bytes_to_merge_at_max_space_in_pool = 1; -- keep both parts
INSERT INTO t VALUES (1, 0.0, 1, 'stale');
INSERT INTO t VALUES (1, -0.0, 2, 'winner');
SELECT * FROM t FINAL PREWHERE toString(f) = '0';
-- 1  0  1  stale   on default settings

FINAL's winner is the -0.0 row, which stringifies as -0, so the answer should be empty; apply_prewhere_after_final = 1 does return empty. isPrewhereDeferredAfterFinal consults only that setting and the deferred row policy, never the predicate. The setting's description names this exact case, so the pre-FINAL default may be intended when the user writes PREWHERE explicitly. Is that so for a float sorting key as well, or should the same screen apply there? I will send a PR if you want one.

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants