Repository navigation
Conversation
…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]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold
Two things I checked independently rather than taking from the implementation notes. The narrowed set cannot affect a non- On whether this is one site out of several: the sibling carriers of the same invariant are already Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260925-015700 |
|
Workflow [PR], commit [c85e6e2] AI ReviewSummaryThis PR narrows Findings❌ Blockers
Final VerdictStatus: Minimum required action: close the remaining explicit- |
| , 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())} |
There was a problem hiding this comment.
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.
|
closing in favor of #121350 |
|
Understood, folding into #121350 is right: its One thing that dies with this PR, if it is worth keeping. #121350's new block in Separately, one measurement from validating the guard: an explicit 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 settingsFINAL's winner is the |
Related: #121782
Related: #121350
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results from
SELECT ... FINALwithoptimize_move_to_prewhere_if_finalenabled when a condition is over a floating-point sorting key column.-0.0and0.0are one key for theFINALmerge, as are allNaNpayloads, so a condition such astoString(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 toPREWHEREunderFINAL.Description
On 26.8-lts and 26.9-stable, a
SELECT ... FINALover aFloat64sorting key returns the superseded row(1, 0, 1)instead of the empty result:#121782 fixed the row policy half; this is the follow-up for the
PREWHEREhalf, which needs no policy at all.Root cause: a conjunct may move to
PREWHEREunderFINALif it is deterministic over the sorting key, which would give one verdict per deduplication group. True for value identity, but theFINALcomparator is coarser for floats:toStringseparates what it merges.Change:
MergeTreeWhereOptimizerexcludes float-containing sorting key columns from the set that authorises the move. One site, both entry points, fewer conditions moved and only underFINAL.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.cppblock 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 theNaN,Nullable(Float64),Tupleand doubly nested cases on thePREWHEREside, 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]