Skip to content

Defer row policies over float sorting key columns after FINAL - #121782

Merged
yakov-olkhovskiy merged 9 commits into
masterfrom
yarik/row-policy-final-float-sorting-key
Sep 24, 2026
Merged

yakov-olkhovskiy merged 9 commits into
masterfrom
yarik/row-policy-final-float-sorting-key

Conversation

@yariks5s

@yariks5s yariks5s commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

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):

Row policies over floating-point sorting key columns are now applied after FINAL (with apply_row_policy_after_final enabled), and such columns are excluded from index analysis of deferred filters. Previously a policy condition distinguishing -0.0 from 0.0 or NaN payloads could filter out the winning row version before the merge and return stale data.


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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9866864]

Summary: ✅


AI Review

Summary

This PR fixes the apply_row_policy_after_final path for float-containing ORDER BY columns and adds good coverage for deferred-filter index analysis. That part looks consistent, but the same FINAL safety rule is still missing from the shared WHERE-to-PREWHERE optimizer, so the broader stale-row bug is not fully closed yet.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:136-148, src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:184-202, 423-430, 832-868] The PR introduces a float-aware "safe before FINAL" key set for row policies, but MergeTreeWhereOptimizer still uses the old sorting_key_names check when optimize_move_to_prewhere_if_final = 1. A predicate like toString(f) = '0' on ReplacingMergeTree with ORDER BY (id, f) is therefore still treated as safe, moved into PREWHERE, and can discard the winning -0.0 / different-NaN row before deduplication, returning stale data. This affects both planner entry points because the ActionsDAG overload also goes through optimizeImpl.
    Suggested fix: reuse the same float-aware "safe before FINAL" helper in MergeTreeWhereOptimizer::isDeterministicExpressionOverSortingKey, and add a focused regression for optimize_move_to_prewhere_if_final = 1 with the 0.0 / -0.0 repro.
Tests
  • ⚠️ tests/queries/0_stateless/05241_row_policy_after_final_float_sorting_key.sql covers row policies and deferred-filter index analysis, but there is still no regression test for the MergeTreeWhereOptimizer sibling path (WHERE -> PREWHERE under FINAL). Add one alongside the existing float-key repro so this gap stays closed.
Final Verdict

❌ Needs changes before merge: FINAL queries can still return stale rows when optimize_move_to_prewhere_if_final = 1, so the float-key correctness rule is not yet applied consistently across the affected MergeTree paths.

LLVM Coverage Report

Measured on commit 9866864.

Metric Baseline Current Δ
Lines 88.20% 88.10% -0.10%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.40% -0.10%

Changed lines: Changed C/C++ lines covered: 50/50 (100.00%) · 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 23, 2026
@yariks5s yariks5s changed the title Yarik/row policy final float sorting key Defer row policies over float sorting key columns after FINAL Sep 23, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 23, 2026
Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
@yakov-olkhovskiy yakov-olkhovskiy self-assigned this Sep 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 986686410 with master 1b5715814 (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

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

Job report

-- the policy hides the winner (1, -0.0, 2), the stale (1, 0.0, 1) must not reappear
SELECT '= the stale version stays hidden =';
SELECT id, f, v FROM t_rp_float_key FINAL;
SELECT id, f, v FROM t_rp_float_key FINAL SETTINGS use_skip_indexes_if_final = 1;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(found by an agent) This query can't fail. use_skip_indexes_if_final_exact_mode defaults to 1, and its second pass re-expands the pruned ranges, so the result is empty whether or not the float atoms are excluded from index analysis. Please add use_skip_indexes_if_final_exact_mode = 0 here. Checked on 26.10.1.551 with a policy shaped to take the deferral path (deleted = 0 AND toString(f) = '0', set(0) index on toString(f)): empty at exact_mode = 1, stale row 1 0 1 at exact_mode = 0.

Also, NaN is never tested, neither nested like Tuple(Float64, UInt8) or Nullable(Float64) - would be nice to have it for coverage.

Comment on lines +136 to +151
NameSet sortingKeyNamesSafeBeforeFinal(const KeyDescription & sorting_key)
{
NameSet names;
for (size_t i = 0; i < sorting_key.column_names.size(); ++i)
{
bool has_float = isFloat(removeLowCardinalityAndNullable(sorting_key.data_types[i]));
sorting_key.data_types[i]->forEachChild([&](const IDataType & child)
{
if (!has_float && WhichDataType(child).isFloat())
has_float = true;
});
if (!has_float)
names.insert(sorting_key.column_names[i]);
}
return names;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

apparently we have the same problem in MergeTreeWhereOptimizer but it's only reachable with no policy at all:

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;
-- returns: 1  0  1  stale     (correct answer is empty)

not a blocker, but we need to either expand this PR or create a follow-up

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai create a follow-up PR for comment above

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before starting I checked for overlap: that fix is already written in #121350, which is open. It adds getSortingKeyNamesSafeBeforeFinal in MergeTreeWhereOptimizer.cpp and builds sorting_key_names from it, so a condition over a float or float-containing sorting key column stops being eligible to move under FINAL, and its test adds the 0.0 / -0.0 ReplacingMergeTree case with an EXPLAIN assertion. Master itself is still unguarded: the constructor at src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:126 builds that set from every sorting key column, and #121782 did not touch the file.

Two gaps still make a separate PR worth having, so I will open one against master unless you would rather not have it:

  • Enable optimize_move_to_prewhere_if_final by default #121350 also flips optimize_move_to_prewhere_if_final to true, so it is not backportable, while the wrong result is reachable on stable releases for anyone who enables the setting explicitly.
  • Its float block covers plain Float64 only. The NaN payload, Nullable(Float64) and Tuple(Float64, UInt8) cases you asked for on the row policy test are not covered on the PREWHERE side.

So: the same guard, no default change, plus the NaN and nested float coverage. If you would rather have all of it land inside #121350, say so and I will drop mine.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Opened as #122142. Confirmed still live after #121782 merged (that change did not touch MergeTreeWhereOptimizer): your reproducer returns 1 0 1 stale on a build of current master, and the new test covers NaN payloads, Nullable(Float64), Tuple(Float64, UInt8) and Array(Tuple(Float64, UInt8)) on the PREWHERE side.

The guard is character-identical to the one already in open #121350, so whichever lands first the other side is a rename and a dropped hunk, and my offer to close mine and fold the coverage into #121350 stands.

Comment thread src/Core/Settings.cpp
If the row policy expression depends only on columns in ORDER BY, it will still be applied before FINAL as an optimization,
since such filtering cannot affect the deduplication result.
If the row policy expression is deterministic and depends only on non-floating-point columns in ORDER BY, it will still be
applied before FINAL as an optimization, since such filtering cannot affect the deduplication result. Floating-point columns

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
applied before FINAL as an optimization, since such filtering cannot affect the deduplication result. Floating-point columns
applied before FINAL as an optimization, since such filtering cannot affect the deduplication result. Floating-point columns or columns containing floating-point (such as Tuple(Float64, …), Array(Float64), Nullable(Float64), etc.)

Comment thread src/Core/Settings.cpp Outdated
Comment on lines 1804 to 1805

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Note: PREWHERE is also deferred, regardless of this setting, whenever a row policy is deferred by
`apply_row_policy_after_final`, because the row policy must be applied before PREWHERE. That happens when the
policy expression is non-deterministic, or reads a column that is not in ORDER BY, or reads an ORDER BY column
whose type is or contains a floating-point type.
Possible values:
- 0 — PREWHERE is applied before FINAL, unless a deferred row policy defers it too (default).
- 1 — PREWHERE is applied after FINAL.

@yakov-olkhovskiy
yakov-olkhovskiy added this pull request to the merge queue Sep 24, 2026
Merged via the queue into master with commit 6b1c9a6 Sep 24, 2026
341 of 342 checks passed
@yakov-olkhovskiy
yakov-olkhovskiy deleted the yarik/row-policy-final-float-sorting-key branch September 24, 2026 23:34
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026
UberDever pushed a commit to UberDever/ClickHouse that referenced this pull request Oct 19, 2026
…mary key column

`buildIndexes` turns `use_skip_indexes_if_final_exact_mode` off when every
column of every useful skip index is in the primary key (ClickHouse#93899): rows of one
FINAL group have equal key values, so such an index cannot drop the winner of
a group while keeping an older version.

For floats that premise is false. The FINAL merge treats -0.0 and 0.0, and all
NaN payloads, as one key, while a skip index stores the actual values. With
rows (1, 0.0, 1) and (1, -0.0, 2) in two parts and `INDEX ix_f f TYPE set(0)`
on key column `f`, `FINAL WHERE toString(f) = '0'` drops the granule with the
winner and returns the superseded row; SummingMergeTree returns a partial sum.

Build the set of primary key columns with `sortingKeyNamesSafeBeforeFinal`,
which excludes float-containing columns for the same reason in deferred row
policies (ClickHouse#121782). A skip index on a float key column now keeps the exact-mode
recovery pass on; for such keys it reads the whole surviving parts, as it
already does for an index on a non-key column of these tables. Indexes on
non-float key columns keep the shortcut.

Closes ClickHouse#122346

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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.

4 participants