Skip to content

Do not remove zero rows in SELECT FINAL from SummingMergeTree - #115032

Merged
alexey-milovidov merged 46 commits into
masterfrom
summing-final-all-columns
Oct 11, 2026
Merged

alexey-milovidov merged 46 commits into
masterfrom
summing-final-all-columns

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 16, 2026 •

Copy link
Copy Markdown
Member

SELECT ... FINAL from a SummingMergeTree table returned results that depended on which columns the query read.

A merge removes a row when the values in all of the columns of the summation are zero after summing. The FINAL read applied the same rule, but only over the columns the query happened to read. So SELECT count() FROM t FINAL (which reads a single small column) or SELECT c0, c3 FROM t FINAL could silently drop rows that SELECT * FROM t FINAL returns, and a query reading only the sorting key never removed anything.

Reading every summed column for each FINAL query would make the removal decision consistent, but it degrades performance too much. Instead, SELECT ... FINAL now sums the rows with equal keys and never removes zero rows. Its result no longer depends on the set of columns read. Background merges and OPTIMIZE TABLE ... FINAL still remove zero rows as before, so FINAL can now return all-zero rows that a merge would delete. This is a deliberate backward-incompatible change.

Implementation: a remove_zero_rows parameter on SummingSortedTransform, set to false in addMergingFinal.

Found by the nightly SQLancer FinalMerge oracle (SELECT count() FROM t0 FINAL returned 9947 before OPTIMIZE TABLE t0 FINAL and 9999 after it on the same data): https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=5c9f28ed5a2c585ad46bf74d6600cdcf3aa07a9e&name_0=NightlySQLancer&name_1=SQLancer%20%28arm_asan_ubsan%29&name_1=SQLancer. If the SQLancer oracle compares FINAL with a later OPTIMIZE ... FINAL, it needs to filter out the all-zero rows.

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

SELECT ... FINAL from SummingMergeTree no longer removes the rows whose summed columns are all zero, unlike background merges. Before, this removal looked only at the columns the query read, so results depended on them: for example, SELECT count() FROM table FINAL could return fewer rows than SELECT * FROM table FINAL.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code


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

Version info

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

A merge of SummingMergeTree removes a row when the values in all of the
columns of the summation are zero after summing. The FINAL read applied
the same rule, but only over the columns the query happened to read: a
query reading a subset of the summed columns (for example, bare count(),
which reads a single smallest column, plus the internally added sorting
key) removed every group whose visible columns summed to zero, even
though an unread summed column made the row survive a real merge. The
rows silently disappeared from the result. Conversely, a query reading
none of the summed columns never removed anything, keeping rows that a
real merge deletes.

Fix by always including all columns that a merge would aggregate into
the FINAL read set (and into the set protected from the plan-level
column pruning), so the removal decision is taken over the same set of
columns as in a real merge.

Found by the SQLancer FinalMerge oracle: SELECT count() FINAL returned
9947 before OPTIMIZE FINAL and 9999 after it on the same data.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=5c9f28ed5a2c585ad46bf74d6600cdcf3aa07a9e&name_0=NightlySQLancer&name_1=SQLancer%20%28arm_asan_ubsan%29&name_1=SQLancer

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b3ef481]

Summary: ✅


AI Review

Summary

This PR changes SummingMergeTree FINAL to keep all-zero rows instead of trying to emulate background-merge deletion from a partial read set, and updates the engine documentation plus stateless coverage to match that new contract. I did not find unresolved correctness, rollout, or metadata issues in the current diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b3ef481b9 with master 2e77cbc01 (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

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

Job report

Comment thread src/Planner/PlannerJoinTree.cpp Resolved
`getColumnsAggregatedForSummingFinal` decided which `...Map` arrays participate in
the merge by the `endsWith(name, "Map")` name convention alone, while
`SummingSortedAlgorithm::defineColumns` promotes a discovered map group only after
validating it (at least two columns, an integer-like key, summable values, no member
of the sorting or partition key). Legal schemas such as `OnlyOneColumnMap Nested(ID UInt32)`
or `NonArithmeticValueMap Nested(ID UInt32, Date Date)` are only copied by a real merge,
yet `SELECT count() ... FINAL` read their arrays in full.

Instead of duplicating the classification, ask the merge algorithm itself: the new
`SummingSortedAlgorithm::getAggregatedColumnNames` runs `defineColumns` over the table
header and returns the columns of `columns_to_aggregate` and `maps_to_sum`. The read set
now cannot drift from what a merge actually aggregates. Columns of a composite-key map
are kept in the set because their presence makes the merge keep every row.

Adds a test for a summed column hidden from both the projection and the `PREWHERE`
predicate, and a test that `FINAL` no longer reads the arrays of a `...Map` group that
the merge rejects.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: test_storage_nats/test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write in Integration tests (arm_binary, distributed plan, 1/4) and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is unrelated to this pull request: the same test fails on master and across many unrelated pull requests (3-13 failures a day over the last month, per play.clickhouse.com), and I could not find an open issue tracking it.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress in #115343, which you opened on 2026-08-18. Same signature as this red: ClickHouse lost some messages: 97281 / assert 97281 == 100000 at test_nats_jet_stream.py:1055.

It is the only red on 0de10a1d, and nothing in this pull request reaches src/Storages/NATS.

One caveat in case #112828 comes up as the owner: that one merged on 2026-08-13 and only recovers a subscription the client had closed, so it does not cover this window. #115343 is the PR to track.

…dy read

With `allow_tuple_element_aggregation`, the `FINAL` read set is extended with the
tuple-flattened leaves of the summed columns. The deduplication compared exact
names only, so a query that reads a whole `Tuple` column got both the tuple and
each of its leaves, and the merge - which flattens the tuple again on its own -
read and aggregated the same numeric leaf twice. Skip a leaf whose ancestor is
already requested.

Also make `05024_summing_final_hidden_column_and_rejected_map` assert the read set
on the pipeline instead of on `read_bytes` of a 200000-row table. The byte
threshold depended on the randomized settings of the flaky check (it failed with
`result differs with reference`) and the inserts made the test time out under
sanitizers (`Test runs too long`). The pipeline assertion needs neither.
…cestors

`SELECT ... FINAL` from a `SummingMergeTree` table with
`allow_tuple_element_aggregation` skipped a flattened leaf only when the query read
the whole top-level tuple, because the covered prefixes were built from the top-level
columns of the metadata sample block. An intermediate tuple subcolumn is a column of
its own in the read set, so `SELECT tup.inner FROM t FINAL` still appended
`tup.inner.c` and `tup.inner.d` next to `tup.inner`, and the merge flattened
`tup.inner` again, reading and aggregating the same leaves twice.

`Nested::flattenTupleRecursive` already reports, for every leaf, the tuple paths it
descends from: the root column and every intermediate tuple. Use them, so a leaf is
skipped whenever any of its ancestors is already read, whatever the depth.
The `Stateless tests (amd_msan, flaky check)` job failed on
`05024_summing_final_hidden_column_and_rejected_map`: with the randomized settings, the
pipeline of `SELECT count() FROM summing_final_rejected_map FINAL` contained
`NonArithmeticValueMap.D`, so the assertion that no rejected `...Map` group is read
found four matching header lines instead of none.

That column was not added by the `FINAL` read set: a bare `count()` reads the column
that is cheapest to read, and which column that is follows from the on-disk sizes, so the
randomized `MergeTree` settings (sparse serialization, compact parts, file name hashing)
can make it a `...Map` array. Assert the read set on `SELECT k` instead, which reads the
sorting key plus exactly the columns the merge requires.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115032&sha=64b9870e50cbe21a3fa4582223d42ec502831b6e&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20flaky%20check%29
#115032

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

🕵 Publishing the replies to the earlier findings on this pull request.

Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Replace the previous approach (always reading every summed column for
`FINAL`) with the opposite one, as requested in the review: `FINAL` sums
the rows with equal keys but never removes the rows whose sums are all
zero. A query may read only a subset of the summed columns, so it cannot
decide whether a row is zero the way a merge does; reading all summed
columns to make that decision would degrade performance too much.

This is backward incompatible: `SELECT ... FINAL` now returns all-zero
rows that a background merge would delete. The result no longer depends
on the set of columns the query reads (e.g. `SELECT count() FROM t FINAL`).

Revert all changes of this PR in `ReadFromMergeTree`, `ExpressionAnalyzer`,
`PlannerJoinTree` and `SummingSortedAlgorithm`, add a `remove_zero_rows`
parameter to `SummingSortedTransform` and pass `false` from
`addMergingFinal`. Update `03802_summing_merge_tree_tuple_element`, which
pinned the removal of zero rows under `FINAL`, and the engine docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov changed the title Read all summed columns for SELECT FINAL from SummingMergeTree Do not remove zero rows in SELECT FINAL from SummingMergeTree Oct 8, 2026
@alexey-milovidov alexey-milovidov added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 8, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Reworked as requested in 5c39dfe: the approach that read every summed column for FINAL is completely reverted (ReadFromMergeTree, ExpressionAnalyzer, PlannerJoinTree, SummingSortedAlgorithm, and its tests). SELECT ... FINAL from SummingMergeTree now never removes zero rows: addMergingFinal passes a new remove_zero_rows = false to SummingSortedTransform. Merges still remove them. I marked the PR as Backward Incompatible Change and updated 03802_summing_merge_tree_tuple_element, which expected FINAL to drop zero rows. I added 05339_summing_final_keeps_zero_rows, and updated the engine docs in registerStorageMergeTree.cpp. Locally, all stateless tests that mention SummingMergeTree pass except the ones that need ZooKeeper or clusters, which my bare test server doesn't have. The SQLancer FinalMerge oracle will need to account for the all-zero rows on its side.

alexey-milovidov and others added 5 commits October 8, 2026 16:25
…ows kept by `FINAL`

`SELECT ... FINAL` from `SummingMergeTree` no longer removes the rows whose
summed columns are all zero, so the row with `value = 0` is now returned
before the merge. After `OPTIMIZE TABLE ... FINAL` it is still removed.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115032&sha=5c39dfe7245372cc65c2cccb80c4c17478a2e887&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
#115032

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`03280_json_subcolumns_in_primary_key_select_final` expects the row with
`value = 0` in `SELECT ... FINAL`, but with `optimize_on_insert = 1` (the
default, used by the fast test) the insert itself removes that row, so
the result depended on the randomized setting. Pin `optimize_on_insert = 0`.

`03802_summing_merge_tree_tuple_element` Test 8 now expects the zero rows in
`SELECT ... FINAL`, so stop merges for that table until `OPTIMIZE`, otherwise
a background merge could remove them first.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115032&sha=1379e50b79507a52d1f0b61dc18d64dcddebd204&name_0=PR&name_1=Fast%20test
#115032

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

Copy link
Copy Markdown
Member Author

🕵 The red Build (arm_tidy, 2/4) was use of undeclared identifier 'FifoQueue' in gtest_throttler_constraint.cpp. This PR does not touch that file, and master already fixes it in be9cfb18407 ("Fix tidy build"). I merged master in 25705c6.

alexey-milovidov and others added 2 commits October 10, 2026 12:06
…geTree` to the zero-row removal

`FINAL` still depends on the read set for nested `...Map` structures: if
the query reads only some of their columns, they are not merged the way a
merge does. Say so in the engine documentation.

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

Copy link
Copy Markdown
Member Author

🕵 The red 05316_secret_arguments_declared_by_engines in Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) is unrelated to this PR and is fixed on master by 351f549fe5b ("Fix 05316_secret_arguments_declared_by_engines with Replicated database"). I merged master in 2f59822 to pull it in, and addressed the open review thread about ...Map nested structures in b3ef481.

@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 a big relief!

@alexey-milovidov alexey-milovidov self-assigned this Oct 11, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 11, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The SQLancer FinalMerge oracle will need to account for the all-zero rows on its side.

@groeneai, please correct the SQLancer oracle (or remove it if it cannot be repaired). Send a new PR.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm fixing the SQLancer FinalMerge oracle in ClickHouse/sqlancer so it accounts for the all-zero SummingMergeTree rows that FINAL now keeps; I'll follow up here with the PR link.

Merged via the queue into master with commit b8b931f Oct 11, 2026
164 checks passed
@alexey-milovidov
alexey-milovidov deleted the summing-final-all-columns branch October 11, 2026 18:54
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

The fix is ClickHouse/sqlancer#22. For SummingMergeTree, FinalMerge now compares countIf(NOT (c1 = 0 AND ...)) over the integer and Decimal columns that the merge always sums, instead of count(), so the all-zero rows that FINAL keeps drop out of both reads. The check holds with and without this PR: against this PR's amd_release build the old oracle reported 38 mismatches in 4 minutes, the fixed one none in 15.

fm4v pushed a commit to ClickHouse/sqlancer that referenced this pull request Oct 12, 2026
… SummingMergeTree

ClickHouse/ClickHouse#115032 makes `SELECT ... FINAL` from `SummingMergeTree`
keep the rows whose summed columns are all zero, while background merges and
`OPTIMIZE TABLE ... FINAL` still delete them. The FinalMerge oracle compared
`count()` under `FINAL` before and after `OPTIMIZE ... FINAL`, so on a server
with that change it reports every all-zero group as a mismatch.

For a SummingMergeTree table both reads now count only the rows where at least
one summed column is non-zero: `countIf(NOT (c1 = 0 AND ...))`. The columns are
the integer and Decimal columns that the merge sums for certain: not in the
sorting or partition key, physically stored, and listed in the engine's
`columns` argument when there is one. Any row the merge deletes has all of them
equal to zero, so it is excluded from both counts and the comparison holds with
and without #115032. Float columns are left out because a float sum can be zero
in one summation order and not in another. A table without such a column is
skipped, and so is a table with an unfinished mutation, whose columns may not
be readable. `countIf` rather than `WHERE` keeps the predicate from being moved
before the merge under `optimize_move_to_prewhere_if_final`.

Other engines keep the plain `count()` comparison.

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-backward-incompatible Pull request with backwards incompatible changes 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.

3 participants