Skip to content

Fix SummingMergeTree FINAL dropping rows when column pruning hides non-zero summing columns - #106135

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-106125-summing-final-column-pruning
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-106125-summing-final-column-pruning

Conversation

@groeneai

@groeneai groeneai commented May 29, 2026 •

Copy link
Copy Markdown
Collaborator

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 SELECT FINAL on a SummingMergeTree table silently dropping a physically-present row when column pruning narrowed the read set to a subset of the summing columns and the only visible summing column was zero for that row. The "drop the group's row when all summing columns are zero" rule is now evaluated over the full set of physical summing columns from the table metadata, matching real on-disk merge semantics.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Description

SELECT FINAL on a SummingMergeTree could silently drop a physically-present row when column pruning narrowed the read set to a strict subset of the summing columns and the only visible summing column was 0 for that row. A real on-disk merge keeps the row because another (pruned) summing column has a non-zero value.

Root cause: SummingSortedAlgorithm applies a "drop the group's row if all summing columns are zero" rule over the summing columns present in its input header. That header is the table sample block, i.e. every physical column (ordinary plus materialized). ReadFromMergeTree already pins sign_column / version_column / is_deleted_column for Collapsing / Replacing / VersionedCollapsing so those algorithms see complete row state under FINAL; the Summing branch was missing the same treatment. The same gap existed in getColumnsRequiredForMergingFinal, used by the removeUnusedColumns query-plan optimization.

Both read-set paths now share one helper that mirrors SummingSortedAlgorithm::defineColumns' membership exactly, so the on-the-fly FINAL path and a real merge keep/drop the same rows:

  • All physical columns via getAllPhysical(), so a materialized non-key numeric column is preserved. (An earlier revision used getOrdinary(), which omits materialized columns and could still drop a row whose only non-zero value lives in one.)
  • An explicit columns_to_sum entry that names a Nested table, e.g. SummingMergeTree(SomeMap) whose stored columns are SomeMap.ID / SomeMap.Num, is expanded to its physical subcolumns the way the engine matches columns_to_sum. A *Map Nested member is kept regardless of columns_to_sum, because the algorithm discovers and sums maps independently of the scalar columns_to_sum filter.
  • A non-summable scalar (e.g. a String column) is pruned: the algorithm copies it last-value and it never affects the zero-row decision, so it is not read from disk.
  • With allow_tuple_element_aggregation, the algorithm flattens Tuple columns (Nested::flattenTupleRecursive) and sums the leaves, so a Tuple column is kept when any flattened leaf is summable. The whole physical column is read, which gives the merge every leaf. The tuple recursion mirrors defineColumns' flattened-leaf gates: a *Map-suffixed array leaf is a summed-map candidate only when its synthesized parent is a real tuple ancestor and, with an explicit columns_to_sum, the leaf or an ancestor is named; otherwise it is copied last-value and not pinned, so an unlisted tuple *Map is not over-read.

Reproducer from issue #106125:

CREATE TABLE s (c0 UInt32, v_keep Int32, v_zero UInt32) ENGINE = SummingMergeTree ORDER BY c0;
INSERT INTO s VALUES (0,1,0),(1,1,1),(2,1,2);
INSERT INTO s VALUES (3,1,3),(4,1,4),(5,1,5);
SELECT c0 FROM s FINAL WHERE v_zero >= 0 ORDER BY c0;
-- before: 1,2,3,4,5  (c0=0 incorrectly dropped)
-- after:  0,1,2,3,4,5

Tuple-leaf reproducer (allow_tuple_element_aggregation):

CREATE TABLE s (k UInt64, metrics Tuple(a Int64, b Int64))
ENGINE = SummingMergeTree ORDER BY k SETTINGS allow_tuple_element_aggregation = 1;
INSERT INTO s VALUES (0,(0,1)),(1,(5,5));
INSERT INTO s VALUES (0,(0,0)),(2,(7,7));
SELECT k FROM s FINAL WHERE metrics.a >= 0 ORDER BY k;
-- before: 1,2    (k=0 dropped though metrics.b=1)
-- after:  0,1,2

Validation:

  • New stateless test 04301_106125_summing_final_column_pruning_drops_row.sql covers implicit, explicit, materialized, explicit-Nested-map, explicit-multi-column, non-summable-String, tuple-leaf, nested-tuple and explicit-excluded-tuple cases under FINAL with column pruning. It fails on the unfixed binary and passes with the fix.
  • Existing SummingMergeTree, Coalescing, AggregatingMergeTree, allow_tuple_element_aggregation and remove-unused-columns-under-FINAL stateless tests pass.
  • Semantic check: a row whose summing columns are all zero is still dropped by FINAL; the fix only restores rows whose full stored form has a non-zero summing column. Verified the on-the-fly FINAL result matches a real OPTIMIZE TABLE ... FINAL merge for the tuple case.

Closes #106125

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (self-assessment)

# Question Status
a Deterministic repro? CREATE TABLE s ... SummingMergeTree ORDER BY c0; INSERT ...; SELECT c0 FROM s FINAL WHERE v_zero >= 0 ORDER BY c0; returns 5 rows on master, 6 rows with fix, every run.
b Root cause explained? SummingSortedAlgorithm evaluates "drop row if all summing columns are zero" over the columns visible in its input header. ReadFromMergeTree::spreadMarkRanges pins sign_column / version_column / is_deleted_column for the other merge engines but never pinned columns_to_sum for Summing. With column pruning the read set narrowed to a subset of summing columns, the rule misfired on rows whose pruned-out columns were non-zero. Same gap existed in getColumnsRequiredForMergingFinal used by removeUnusedColumns.
c Fix matches root cause? Pin columns_to_sum (or all ordinary non-key columns when implicit) in both places that determine the read set under Summing FINAL - the same pattern already used for sign/version/is_deleted. Not a band-aid on SummingSortedAlgorithm.
d Test intent preserved + regression test added? New stateless test 04301_106125_summing_final_column_pruning_drops_row covers implicit columns_to_sum, explicit SummingMergeTree(v_zero), count() agreement, SELECT *, and optimize_read_in_order = 0 workaround. Existing tests 00043 / 00084 / 00146 / 00148 / 00625 / 01030 / 01373 / 01913 / 02016 / 02456 / 02785 / 03314 / 03325 / 03409 (Coalescing) / 03411 / 03566 (issue #81303 single-row case) / 03733 / 03751 all pass unchanged.
e Fails without fix, passes with fix? Stashed fix, rebuilt, ran the new test against fresh master HEAD - test FAILED with c0=0 missing. Restored fix, rebuilt, same test - PASSED. Verified both directions on the same binary.
f Fix is general, not narrow patch? The bug class is "engine merge semantic needs all engine-managed columns under FINAL". The codebase already pins sign_column / version_column / is_deleted_column for Collapsing / Replacing / VersionedCollapsing; we extend the same pattern to columns_to_sum for Summing. The fix is at the source (read column set), not at the symptom site (SummingSortedAlgorithm). I considered the sibling engines: Coalescing reuses SummingSortedAlgorithm but with remove_default_values=false, so the zero-row-removal rule never fires - no fix needed. Aggregating uses a separate algorithm with no zero-row-removal - no fix needed. Graphite already disables column pruning entirely.

Session: cron:clickhouse-ci-task-worker:20260529-204500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @alesapin — could you review? The fix pins all summing columns for SummingMergeTree FINAL the same way the existing code pins sign/version/is_deleted for the other merge engines, so SummingSortedAlgorithm sees the full row state and stops dropping rows whose pruned-out columns are non-zero.

@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [58aa91e]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Config Workflow ERROR
Dockers Build (amd) DROPPED
Dockers Build (arm) DROPPED
Dockers Build (multiplatform manifest) DROPPED
Style check DROPPED
Code Review DROPPED
Docs check DROPPED
Docs check (Mintlify) DROPPED
Fast test DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 1, 2026
@fm4v fm4v added the can be tested Allows running workflows for external contributors label Jun 4, 2026
@groeneai
groeneai force-pushed the fix-106125-summing-final-column-pruning branch from add80f5 to f557421 Compare June 10, 2026 19:30
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Both concerns were real correctness gaps in the previous revision and are now fixed. I rebased onto current master (f557421) and reworked both read-set paths to share one helper, getSummingColumnsRequiredForFinal, that mirrors SummingSortedAlgorithm's column source exactly.

1. Nested table name in columns_to_sum. Confirmed: with SummingMergeTree((SomeMap)) the engine stores the prefix SomeMap in columns_to_sum, while the physical columns are SomeMap.ID / SomeMap.Num. The previous revision pinned the literal SomeMap, which is not a physical column, so SELECT k FROM ... FINAL failed with Code: 10 ... Column 'SomeMap' not found in table. The helper now expands an entry to its physical subcolumns using the same match the engine uses for columns_to_sum validation (Nested::extractTableName). Verified SELECT k FROM nm FINAL returns 0, 1 instead of erroring; added a nested-* case to the regression test.

2. Materialized physical summing columns. Confirmed: the merge header is the table sample block (getAllPhysical() = ordinary + materialized), so a materialized non-key numeric column participates in the zero-row rule. The previous revision used getOrdinary() and missed it. For your exact reproducer (v_keep Int32 MATERIALIZED 1), SELECT c0 FROM s FINAL WHERE v_zero >= 0 dropped the c0 = 0 row. The helper now keeps all physical columns via getAllPhysical(); that query now returns 0, 1, 2. Added a mat-* case to the regression test.

Both paths (spreadMarkRanges and getColumnsRequiredForMergingFinal) call the one helper, so they can no longer diverge.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Materialized: CREATE TABLE s (c0 UInt32, v_keep Int32 MATERIALIZED 1, v_zero UInt32) ENGINE = SummingMergeTree ORDER BY c0; INSERT INTO s (c0, v_zero) VALUES (0,0),(1,1),(2,2); SELECT c0 FROM s FINAL WHERE v_zero >= 0 ORDER BY c0; returns 1,2 unfixed, 0,1,2 fixed. Nested: CREATE TABLE nm (k UInt64, SomeMap Nested(ID UInt32, Num Int64)) ENGINE = SummingMergeTree((SomeMap)) ORDER BY k; ... SELECT k FROM nm FINAL errors NOT_FOUND_COLUMN_IN_BLOCK unfixed, returns 0,1 fixed.
b Root cause explained? Yes. SummingSortedAlgorithm evaluates "drop the group's row when all summing columns are zero" over the summing columns in its input header, which is the table sample block (all physical columns). When FINAL column pruning narrows the read set to a strict subset, a row non-zero only in a pruned summing column is wrongly dropped. The previous revision's getOrdinary() excluded materialized columns, and pinning the literal Nested prefix requested a non-existent physical column.
c Fix matches root cause? Yes. The read set is now built from getColumns().getAllPhysical() (the exact source of the algorithm's header), minus key columns, with explicit Nested entries expanded to physical subcolumns via Nested::extractTableName, matching the engine's own columns_to_sum matching.
d Test intent preserved / new tests added? Yes. 04301 is extended with mat-* (materialized), nested-* (explicit Nested map) and multi-* (explicit multi-column) cases under FINAL with pruning. No existing assertions weakened.
e Both directions demonstrated? Yes. Built the unfixed binary (drops the row / errors) and the fixed binary (correct) and compared all cases. 04301 output matches its reference on the fixed binary.
f Fix is general, not a narrow patch? Yes. Both read-set sites share one helper, so they cannot diverge. The implicit, explicit, materialized, Nested-map and multi-column cases are all handled by the same metadata-driven selection. Sibling merge modes (Collapsing/Replacing/VersionedCollapsing) already pin their state columns; Coalescing keeps its existing semantics. 27 existing Summing/Coalescing/remove-unused-columns-under-FINAL tests pass.

Session id: cron:clickhouse-worker-slot-22:20260610-184200

@groeneai
groeneai force-pushed the fix-106125-summing-final-column-pruning branch from f557421 to f01b49f Compare June 10, 2026 23:14
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the over-broad pinning in f01b49fd5599.

The implicit-mode helper no longer pins every physical column. It now pins a non-key physical column only if SummingSortedAlgorithm::defineColumns (with aggregate_all_columns=false, the query-time FINAL path) would route it into columns_to_aggregate or a summed map: a summable scalar (isSummable()), an AggregateFunction/SimpleAggregateFunction, or an array member of a *Map-suffixed Nested table. Columns the algorithm leaves in column_numbers_not_to_aggregate (a String, a plain non-Map array) are copied last-value and never change the keep/drop outcome, so they stay prunable. The new isSummingColumnRelevantForFinal mirrors that dispatch; the scalar branch calls the same isSummable() predicate, so there is no divergence for scalars. Over-keeping a *Map group that discovered_maps later rejects is safe; under-keeping would reintroduce the dropped-row bug.

Verified: the issue reproducer returns all 6 rows; den-crane's no-WHERE reproducer still correctly drops id=1 when its summed value is 0 (the summable column stays pinned even when projected out); a String non-key column is now pruned without keeping a zero-summing row alive; and 04301 still passes (and still fails on master HEAD).

@groeneai
groeneai force-pushed the fix-106125-summing-final-column-pruning branch from f01b49f to 5e675ed Compare June 11, 2026 00:22
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the two follow-up reviews. They pull in opposite directions, and you are right on both — the previous revision split getSummingColumnsRequiredForFinal into an explicit branch (name-only, too narrow for *Map) and an implicit branch (type-filtered). I have reworked it into a single per-column predicate applied to every non-key physical column, mirroring defineColumns' dispatch in the query-time path (aggregate_all_columns=false) so the two cases cannot diverge.

A column is kept iff defineColumns would route it into columns_to_aggregate or a summed map:

  • a *Map-suffixed Nested array member — regardless of columns_to_sum, because map discovery happens independently of, and before, the scalar columns_to_sum filter;
  • a scalar / (Simple)AggregateFunction that is summable (or an aggregate function) and, under an explicit columns_to_sum, named in it.

Everything else (String, plain non-Map array, a scalar absent from an explicit columns_to_sum) goes to column_numbers_not_to_aggregate, never affects the keep/drop outcome, and stays prunable.

This fixes both notes at once:

  • 23:19Z (too narrow): CREATE TABLE s (k UInt64, v UInt64, SomeMap Nested(ID UInt32, Num Int64)) ENGINE = SummingMergeTree(v) ORDER BY k now pins SomeMap.ID/SomeMap.Num, so SELECT k FROM s FINAL WHERE v >= 0 keeps the v-sums-to-0, map-present row.
  • 19:34Z (too broad): CREATE TABLE s (k UInt64, payload String, v UInt64) ENGINE = SummingMergeTree ORDER BY k no longer reads payload under SELECT k FROM s FINAL (payload is absent from the plan; it can never keep a zero-v row).

New regression cases added to 04301: sum-and-map-* (explicit scalar + Nested map) and payload-string-* (non-summable scalar pruned). 50/50 random-settings runs pass; existing 00146_summing_merge_tree_nested_map, 00084_summing_merge_tree, 00915_simple_aggregate_function*, 01030_final_mark_empty_primary_key and the Coalescing tests still pass.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. 23:19Z: SummingMergeTree(v) + SomeMap Nested, SELECT k FROM s FINAL WHERE v>=0 drops k=0 on the prior commit (f01b49), returns it after. 19:34Z: EXPLAIN actions=1 SELECT k FROM s FINAL shows payload absent from the read plan with the fix.
b Root cause explained? SummingSortedAlgorithm::defineColumns (query path) discovers *Map Nested arrays into discovered_maps and sums them independently of columns_to_sum; in startGroup, a non-empty maps_to_sum sets current_row_is_zero=false. Pruning the map columns leaves only scalar v in columns_to_aggregate, so current_row_is_zero=true when v sums to 0 and the row is dropped — diverging from a real merge. Symmetrically, a non-summable String is placed in column_numbers_not_to_aggregate and never affects the decision, so pinning it only forces needless reads.
c Fix matches root cause? Yes. One predicate reproduces defineColumns' exact membership: *Map member (regardless of columns_to_sum), or summable/agg scalar (named, if explicit). It does not widen bounds, add no-random-*, or guard a symptom.
d Test intent preserved / new tests added? Preserved and extended. 04301 keeps all prior cases and adds sum-and-map-* (the 23:19Z scenario) and payload-string-* (the 19:34Z scenario, asserting correct drop of the zero-v row).
e Both directions demonstrated? Yes. 23:19Z case: prior commit f01b49 returns 1,2 (drops k=0, count=2); fixed returns 0,1,2 (count=3), SELECT * ground truth confirms k=0 with SomeMap.Num=[150]. Bidirectional build verified.
f Fix is general, not a narrow patch? Yes. Both read sites (spreadMarkRanges and getColumnsRequiredForMergingFinal, the latter feeding removeUnusedColumns) call the same helper, so they cannot diverge. The predicate covers ordinary, materialized, explicit-scalar, explicit-Nested-prefix, scalar+standalone-*Map, (Simple)AggregateFunction and non-summable-scalar columns. The fix targets the read-set computation, not the crash site.

Session id: cron:clickhouse-worker-slot-19:20260610-235100

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on `5e675eddba54`. All failures are the same infrastructure outage, not caused by this PR (SummingMergeTree FINAL column-pruning fix):

  • `Stateless tests (arm_asan_ubsan, azure, parallel + sequential)` — `Server died` / `AddressSanitizer` (STID 1003-326e) / `Segmentation fault` (STID 0883-49e8) / `00985_merge_stack_overflow`: the Azure arm_asan_ubsan mass outage of 2026-06-10/11 (ASan secondary-allocator OOM, no ClickHouse frames). These STIDs hit 20 PRs in the last 2 days. Not PR-related.

The materialized-physical-summing-column gap flagged by the bot is addressed on this HEAD (selection now mirrors SummingSortedAlgorithm via getAllPhysical, with a materialized-column regression test). Ready for review.

@fm4v

fm4v commented Jun 12, 2026

Copy link
Copy Markdown
Member

@groeneai check CI

@groeneai
groeneai force-pushed the fix-106125-summing-final-column-pruning branch from 5e675ed to 74ff199 Compare June 12, 2026 11:32
@groeneai

Copy link
Copy Markdown
Collaborator Author

@fm4v CI was green on the fix itself. On the prior head 5e675ed, Finish Workflow and Mergeable Check both passed; the only failures were two Stateless tests (arm_asan_ubsan, azure) jobs, and both were ASan crashes in the INSERT/part-write path (Quarantine::DoRecycle / CHECK failed: sanitizer_allocator_secondary.h via MergeTreeDataPartWriterWide::finish, MergeTreeSink::consume, WriteBufferFromAzureBlobStorage), not the SummingMergeTree FINAL read path this PR touches.

Root cause was a stale base, not this change. The head was committed 2026-06-11 00:21Z, before #107122 (revert of "Multi-stage distributed queries" #106020) merged at 01:37Z. That revert fixed exactly this ASan heap corruption on master. git compare confirms the old head was behind the revert by 215 commits while still containing the buggy #106020 merge.

Fix: rebased onto current master (now includes #107122) and force-pushed. New head 74ff199. The two ASan crashes should clear on the rerun; the column-pruning change compiles clean against current master and the FINAL fix verification is unchanged.

@groeneai
groeneai force-pushed the fix-106125-summing-final-column-pruning branch from 74ff199 to ae1795f Compare June 12, 2026 13:14
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the 2026-06-12 review on ReadFromMergeTree.cpp (the allow_tuple_element_aggregation tuple-leaf family). The read-set helper now mirrors SummingSortedAlgorithm::defineColumns for tuple flattening too: when allow_tuple_element_aggregation is set, a Tuple physical column is descended (Nested::tryGetFlattenableTuple / recursive leaf walk) and kept whenever any flattened leaf is a summable leaf, with the explicit-columns_to_sum ancestor match handled the same way isColumnOrAncestorInNames does. Both read sites (spreadMarkRanges and getColumnsRequiredForMergingFinal -> removeUnusedColumns) call the one helper.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE TABLE s (k UInt64, metrics Tuple(a Int64, b Int64)) ENGINE = SummingMergeTree ORDER BY k SETTINGS allow_tuple_element_aggregation = 1; then INSERT VALUES (0,(0,1)),(1,(5,5)); INSERT VALUES (0,(0,0)),(2,(7,7)); SELECT k FROM s FINAL WHERE metrics.a >= 0 ORDER BY k returns 1,2 on the prior build (drops k=0) every time; 0,1,2 with the fix.
b Root cause explained? Under allow_tuple_element_aggregation, defineColumns flattens Tuple columns via Nested::flattenTupleRecursive and sums the resulting leaves (metrics.a, metrics.b). The read-set helper walked unflattened getAllPhysical(), saw metrics as one opaque Tuple (not summable, not a *Map array), and pruned it. Column pruning then read only k+metrics.a, the zero-row rule fired on that subset, and the k=0 group (whose metrics.b = 1 survives a real merge) was dropped.
c Fix matches root cause? Yes. The helper now descends flattenable Tuple columns with the same predicate defineColumns uses on its flattened header and keeps the physical column when any leaf is summable. This is not a widening or a guard; it reproduces the algorithm's own membership. The non-tuple path (scalars, *Map, materialized, non-summable String) is unchanged.
d Test intent preserved / new tests added? Yes. Extended 04301_106125_...sql/.reference with: tuple-* (the bot's exact Tuple(a,b) shape), tuple-nested-* (Tuple(a, inner Tuple(c,d)) kept by a deep leaf), and tuple-excluded-* (SummingMergeTree(other) where the unlisted tuple is copied, NOT summed, so the k=0 zero-other row is correctly dropped and metrics is not over-pinned). The existing implicit/explicit/materialized/Nested-map/multi-column/String cases are retained.
e Both directions demonstrated? Yes. Prior build (Build ID f69e587a): the new test FAILS on exactly tuple-projection-only-k and tuple-nested-projection-only-k (each drops 0). Fixed build (6c624bfe): PASSES, --test-runs 50 with full randomization 50/50. Also confirmed on-the-fly FINAL equals a real OPTIMIZE TABLE ... FINAL merge for the tuple case (both 0,1,2, metrics=(0,1) retained).
f Fix is general, not a narrow patch? Yes. One predicate at both read sites (spreadMarkRanges + getColumnsRequiredForMergingFinal) so they cannot diverge. It covers all summing-column families defineColumns recognizes: summable scalars, (Simple)AggregateFunction, *Map Nested groups, materialized physical columns, and now flattened Tuple leaves; non-summable scalars stay pruned (no extra disk reads). The fix is at the source of the divergence (the read-set selection), not a guard at the symptom.

Session id: cron:clickhouse-worker-slot-3:20260612-121000

@groeneai
groeneai force-pushed the fix-106125-summing-final-column-pruning branch from ae1795f to b27d516 Compare June 12, 2026 15:33
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the 2026-06-12 review on ReadFromMergeTree.cpp (the unlisted tuple *Map over-pin). tupleHasSummableLeafForFinal now threads the leaf's true tuple-ancestor paths (built exactly as Nested::flattenTupleRecursive builds flatten_ancestors) and mirrors defineColumns' flattened-leaf map gates: a *Map-suffixed array leaf is a summed-map candidate only when its synthesized parent is a real tuple ancestor (is_real_map) AND, with an explicit columns_to_sum, the leaf or an ancestor is named (excluded_by_columns_list). Scalars/aggregates use the same isColumnOrAncestorInNames-equivalent ancestor check. Both read sites still call the one helper.

A note on the over-pin: I could not produce a stable runtime signal for it. On the bot's exact shape (SummingMergeTree(other), unlisted metrics Tuple(ratesMap Tuple(...))), SELECT k FROM s FINAL WHERE other >= 0 reads only k+other on both the prior commit and this one (cold-cache ProfileEvents['FileOpen'] = 2, ReadCompressedBytes ~160 KB on both; metrics is 10 MB on disk and is never materialized either way), and results are identical. The change is a read-set-list precision fix that mirrors defineColumns; it has no observable read/result regression on its own. So rather than commit a flaky FileOpen-count test, the regression added covers the correctness-bearing tuple-*Map families, including the implicit case that this whole PR fixes.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes, for the correctness-bearing case. CREATE TABLE s (k UInt64, v Int64, metrics Tuple(ratesMap Tuple(ID Array(UInt32), Value Array(Int64)))) ENGINE = SummingMergeTree ORDER BY k SETTINGS allow_tuple_element_aggregation = 1; then two inserts of (0,0,(([1],[100])))…(0,0,(([1],[50])))…; SELECT k FROM s FINAL WHERE v >= 0 ORDER BY k returns 1,2 on plain master (drops k=0) every time, 0,1,2 with the fix. For the bot's unlisted-other shape the result is 1,2 on both (row legitimately drops, see note above).
b Root cause explained? Under allow_tuple_element_aggregation, defineColumns flattens Tuple columns and sums the resulting leaves, including *Map array leaves discovered from a flattened tuple. The prior helper kept every *Map-suffixed flattened leaf, ignoring two guards defineColumns applies (lines 375-403): the leaf's synthesized parent must be a real tuple ancestor, and (with an explicit columns_to_sum) the leaf or an ancestor must be named. So an unlisted tuple *Map was added to the read-set list even though the algorithm copies it last-value and it cannot keep a zero-sum group.
c Fix matches root cause? Yes. The helper now carries flatten_ancestors-equivalent data and applies the same is_real_map and explicit-columns_to_sum checks defineColumns uses on flattened leaves, at both read sites. It reproduces the algorithm's membership, not a heuristic or a guard.
d Test intent preserved / new tests added? Yes. Extended 04301_106125_...sql/.reference with tuple-map-implicit-* (tuple-wrapped *Map, implicit summing, k=0 kept by the summed map), tuple-map-listed-* (SummingMergeTree(metrics), map summed via listed ancestor), and tuple-map-unlisted-* (the bot's exact SummingMergeTree(other) shape, k=0 correctly dropped, matching a real merge). Existing implicit/explicit/materialized/Nested-map/multi-column/String/tuple-scalar cases retained.
e Both directions demonstrated? Yes. Built both binaries. Plain master fails the full 04301 test (10 diff hunks, including tuple-map-implicit-projection-only-k missing 0); the fix passes the full test (exact .reference match). Verified each new case's on-the-fly FINAL equals a real OPTIMIZE TABLE … FINAL (ground truth). 50/50 runs pass; results stable across min_bytes_for_wide_part 0 / 1e9, index_granularity=1, index_granularity_bytes=1024.
f Fix is general, not a narrow patch? Yes. One predicate at both read sites (spreadMarkRanges + getColumnsRequiredForMergingFinal → removeUnusedColumns) so they cannot diverge. It mirrors defineColumns for every summing-column family: summable scalars, (Simple)AggregateFunction, *Map Nested groups, materialized physical columns, and flattened Tuple leaves (including tuple-nested *Map), with non-summable scalars and unlisted/non-real tuple maps pruned. The fix is at the source (read-set selection), not a guard at a symptom.

Session id: cron:clickhouse-worker-slot-3:20260612-142100

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on b27d516aa69c (the latest tuple-*Map ancestor-gate refinement). Finish Workflow and Mergeable Check both ran; the only red is one unrelated chronic failure, not caused by this PR (which only touches ReadFromMergeTree.cpp SummingMergeTree FINAL column-pruning + the 04301 test).

check failure classification disposition
AST fuzzer (amd_msan) 04312_text_index_lazy_segment_cache_reuse — Cannot find input column ... on its position in inputs of expression actions DAG chronic trunk bug (STID 2409-5283) Not PR-caused. 30-day cross-PR: hits #103112, #104119, #104662, #106629 (all unrelated, 1 each), 0 master. Analyzer/text-index DAG path, unrelated to this PR's column-pruning read-set change. Tracked separately.

CH Inc sync is the non-gating CIDB-staging sync job (not a test). The fix logic and bidirectional verification are unchanged from the validated commits.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD b27d516aa69c. One failure, not PR-caused:

  • AST fuzzer (amd_msan) / 04312_text_index_lazy_segment_cache_reuse — LOGICAL_ERROR: Cannot find input column __table5.b on its position in inputs of expression actions DAG on a fuzzed query combining duplicate column aliases (SELECT 2 AS b, 2 AS b) with ANY LEFT JOIN ... USING and a scalar subquery. This is a chronic trunk analyzer/planner DAG bug (3 distinct unrelated PRs in 14 days, 0 master), tracked separately. It is unrelated to this PR's change (ReadFromMergeTree.cpp column-pinning for SummingMergeTree FINAL).

All other checks pass, including Bugfix validation (functional tests) which independently confirms the fix reproduces the original bug. Ready for re-review.

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Dear @shankar-iyer, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@groeneai
groeneai force-pushed the fix-106125-summing-final-column-pruning branch from b27d516 to 61d98ee Compare July 8, 2026 11:27

/// Keep all of SummingMergeTree's summing columns under FINAL so on-the-fly merging matches a real
/// merge's zero-row rule even when column pruning narrows the read set (see helper above, #106125).
if (data.merging_params.mode == MergeTreeData::MergingParams::Summing)

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.

getSummingColumnsRequiredForFinal fixes the storage read set, but the PREWHERE-before-FINAL path still only knows about sorting/sign/version columns. StorageInMemoryMetadata::getColumnsRequiredForFinal() is still just getColumnsRequiredForSortingKey() (src/Storages/StorageInMemoryMetadata.h:267), both ExpressionAnalyzer and PlannerJoinTree use that stale helper to decide which columns must survive PREWHERE (src/Interpreters/ExpressionAnalyzer.cpp:2081, src/Planner/PlannerJoinTree.cpp:586), and spreadMarkRangesAmongStreamsFinal restores only sorting/sign/version/is_deleted inputs (src/Processors/QueryPlan/ReadFromMergeTree.cpp:1988). That means SELECT c0 FROM s FINAL PREWHERE v_zero >= 0 ORDER BY c0 (or WHERE with optimize_move_to_prewhere_if_final = 1) can still read v_keep here and then strip it before SummingSortedTransform, reproducing the same dropped-row bug. Please thread the same Summing-specific required-column set through the generic FINAL/PREWHERE plumbing and add a focused regression for that path.

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.

The PREWHERE fix still misses subcolumn carriers. getSummingColumnsRequiredForFinal returns the physical summing column name (for the tuple case, metrics), but restorePrewhereInputs only re-adds outputs whose input->result_name matches exactly. PREWHERE on tuple fields is built on the subcolumn name instead (t.a is the input in tests/queries/0_stateless/03445_subcolumns_prewhere_pushdown.reference), so this path still does not preserve the physical tuple before SummingSortedTransform.

That means the original dropped-row bug is still reachable with a supported carrier such as:

CREATE TABLE s (k UInt64, metrics Tuple(a Int64, b Int64))
ENGINE = SummingMergeTree ORDER BY k
SETTINGS allow_tuple_element_aggregation = 1;

INSERT INTO s VALUES (0, (0, 1)), (1, (5, 5));
INSERT INTO s VALUES (0, (0, 0)), (2, (7, 7));

SELECT k FROM s FINAL PREWHERE metrics.a >= 0 ORDER BY k;

metrics.b can still be stripped before the merge, so FINAL sees only metrics.a and can drop k = 0 again. The restore step needs to work by storage column name, not only by exact DAG input name, and the regression test should cover FINAL PREWHERE on tuple/map subcolumns.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Both of your mechanism claims are correct, but I could not reproduce the dropped row, so I am not changing the restore key. Details, all measured on this head (Build ID dd9fb5438b2c961ab7cc3614ce99aa288a9e0989).

Your two cited facts hold. restoreDAGInputs does match by exact input->result_name (ReadFromMergeTree.cpp:182-196), and subcolumn PREWHERE really is built on the subcolumn name. EXPLAIN actions=1 for your exact table gives:

Prewhere filter column: greaterOrEquals(metrics.a, 0_UInt8) (removed)
Actions: INPUT : 0 -> metrics.a Int64 : 0

so the DAG's only input is metrics.a and the physical metrics never matches the name I insert.

Your SQL does not drop the row. Running it verbatim against an OPTIMIZE TABLE ... FINAL oracle:

arm result
SELECT k FROM s FINAL PREWHERE metrics.a >= 0 ORDER BY k 0, 1, 2
oracle 0, 1, 2

Why: ActionsDAG::updateHeader only strips what it consumed. ActionsDAG.cpp:1372-1425 removes the header positions it took as DAG inputs and then passes everything else through:

for (size_t i = 0; i < header.columns(); i++)
    if (!pos_to_remove.contains(i))
        res.insert(header.data[i]);

A subcolumn PREWHERE consumes metrics.a, so the physical metrics is never in pos_to_remove and survives to SummingSortedTransform untouched. The exact-name restore exists to rescue a column the DAG does consume by name and would otherwise drop from its outputs. The two shapes are disjoint: metrics in the PREWHERE needs the restore, metrics.a in the PREWHERE never needed it. EXPLAIN header=1, actions=1 confirms the physical tuple is still there after the filter.

Carrier set. k = 0 sums to zero in the referenced leaf and non-zero in a sibling leaf, so a stripped column would drop it. Each arm against its own optimize_move_to_prewhere = 0 oracle, all 0,1,2 on both sides: tuple subcolumn; the same with WHERE + optimize_move_to_prewhere_if_final = 1; enable_analyzer = 0; Nullable leaf via IS NOT NULL (.null); Map subcolumn (m.keys); Nested subcolumn (n.a); LowCardinality beside the tuple; JSON subcolumn (j.a::Int64). Also clean: mixed subcolumn plus physical in one PREWHERE, tupleElement(metrics,'a'), allow_reorder_prewhere_conditions = 1, optimize_read_in_order = 0, do_not_merge_across_partitions_select_final = 1, and an explicit SummingMergeTree((metrics)) columns_to_sum. allow_tuple_element_aggregation = 1 is required for the leaves to be summed at all, but it does not open the gap.

Sibling site. You asked whether the same blindness affects the other pin, so I mutation-tested both. Neutering the read-set pin in spreadMarkRanges drops k = 0 in the WHERE-moved tuple arm. Neutering the restorePrewhereInputs pin, the seam you name, leaves every subcolumn arm unchanged but fails 04301 on the physical-column PREWHERE cases. So neither site is blind; they cover different shapes, and each is load-bearing for its own. Restoring the file rebuilt bit-identically.

I agree exact-name matching does not cover subcolumn-named inputs. I do not think it reopens this bug, since updateHeader never strips a column it did not consume. Switching to storage-column resolution would widen the restored set without changing any result in the arms above, so I have no failing test to justify it, and I would rather not add a change I cannot back with one. If you have a carrier that actually drops a row, post it and I will fix it.

@groeneai
groeneai force-pushed the fix-106125-summing-final-column-pruning branch from 61d98ee to 3d7ddd4 Compare July 8, 2026 12:49
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

@clickhouse-gh Good catch, confirmed and fixed. The PREWHERE-before-FINAL path did still drop the row on the previous HEAD.

Reproduced on the prior HEAD (build a47e162c): SELECT c0 FROM s FINAL PREWHERE v_keep >= 0 ORDER BY c0 over SummingMergeTree(c0 UInt32, v_keep Int32, v_zero UInt32) ORDER BY c0 with two parts returned [1,2,3,4,5] (drops c0=0), while OPTIMIZE TABLE s FINAL keeps all 6. The c0=0 row has v_keep=1 (non-zero) but v_zero=0; a PREWHERE touching only a subset of summing columns stripped the rest before SummingSortedTransform.

Root cause is exactly as you described: pinning the summing columns in column_names_to_read (getReadTaskColumns) fixes the storage read set, but PREWHERE column survival is decided independently. spreadMarkRangesAmongStreamsFinal already restores sorting/sign/version/is_deleted as PREWHERE outputs (ReadFromMergeTree.cpp:1988), but not the summing columns.

Fix: restore the summing columns as PREWHERE outputs there too, alongside the existing sign/version/is_deleted restore, reusing the same getSummingColumnsRequiredForFinal helper that pins the read set (so the two cannot diverge). I fixed it at this single point rather than in StorageInMemoryMetadata::getColumnsRequiredForFinal() because the summing-column set depends on merging_params (engine-specific), which the engine-agnostic metadata does not hold; spreadMarkRangesAmongStreamsFinal has data.merging_params in scope and is the same place the other merge columns are already restored.

The zero-row decision itself is unchanged: genuinely all-zero groups are still dropped (verified below).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT c0 FROM s FINAL PREWHERE v_keep >= 0 ORDER BY c0 on the 2-part SummingMergeTree above drops c0=0 deterministically on the prior HEAD (both analyzers, requires read-in-order).
b Root cause explained? Yes. PREWHERE column survival is decided by getColumnsRequiredForFinal() (sorting key only); a PREWHERE on a subset of summing columns strips the others before SummingSortedTransform, so its zero-row rule sees a pruned subset and drops a row a real merge keeps.
c Fix matches root cause? Yes. spreadMarkRangesAmongStreamsFinal now restores the full summing-column set as PREWHERE outputs (same mechanism used for sign/version/is_deleted), via the same helper that pins the read set.
d Test intent preserved / new tests added? Yes. Added a s_106125_prewhere section to 04301 covering explicit PREWHERE on a summing column, old analyzer, WHERE moved to PREWHERE (optimize_move_to_prewhere_if_final), and PREWHERE on the zero column. Existing cases unchanged.
e Both directions demonstrated? Yes. Full 04301 PASSES on the fixed binary (03dbdc2a); on the baseline (a47e162c) the two prewhere-v_keep cases are missing the 0 row (diff 138a139, 144a146).
f Fix general across code paths? Yes. Single restore point covers both analyzers (both route PREWHERE through spreadMarkRangesAmongStreamsFinal); the storage-read-set pin and the PREWHERE-output restore now use one shared helper.
g Fix generalizes across inputs? Yes. Verified across implicit/explicit columns_to_sum, wide/compact parts, index_granularity 1/8192; PREWHERE on both a kept and a zero summing column. Zero-row semantics preserved (genuinely all-zero groups still dropped, incl. explicit columns_to_sum).
h Backward compatible? Yes. No setting default, on-disk/wire format, or validation change. Pure query-plan read-set correctness fix; only affects previously-incorrect (dropped-row) results.
i Invariants and contracts preserved? Yes. Only adds inputs to PREWHERE outputs (never removes); SummingSortedAlgorithm's keep/drop rule is untouched. Collapsing/Replacing/Aggregating FINAL+PREWHERE unaffected (guarded by mode == Summing); confirmed zero over-keep of genuinely-zero groups.

Pushed as 3d7ddd4 (amended onto the existing single commit; base is current master). No em-dashes.

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3d7ddd4

Every failure below has an owner (a fixing PR). Only CH Inc sync-class checks are exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) — Error message in clickhouse-server.log infra error-leak: DatabasePostgreSQL::getTablesIterator logs Code 614 connection timeout to the unreachable fixture host 192.0.2.1:5432; unrelated to this PR's SummingMergeTree diff #109350 (ours, open) — allowlists DatabasePostgreSQL getTablesIterator + AsyncLoader upgrade-check connection errors
Mergeable Check / PR aggregator downstream of the above

Session id: cron:our-pr-ci-monitor:20260708-170000

…n-zero summing columns

Closes ClickHouse#106125

A SELECT ... FINAL on a SummingMergeTree table can silently drop a
physically-present row when column pruning narrows the read set to a
strict subset of the summing columns and the only summing column read is
zero for that row. On-the-fly FINAL merging applies SummingSortedAlgorithm's
"drop the group when all summing columns are zero" rule to the pruned
subset, while a real on-disk merge sees the full set and keeps the row.

The read set under FINAL now keeps every physical column that
SummingSortedAlgorithm could sum, mirroring defineColumns' membership
exactly so the on-the-fly path and a real merge agree:

  * implicit columns_to_sum: all summable non-key physical columns;
  * explicit columns_to_sum: a named scalar is kept, an unnamed scalar is
    pruned, and a *Map Nested member is kept regardless of columns_to_sum
    (map discovery ignores the scalar columns_to_sum filter);
  * materialized non-key columns are kept (the merge header is the table
    sample block, which includes them);
  * a non-summable scalar (e.g. String) is pruned (it never affects the
    zero-row decision), so no unnecessary disk reads;
  * with allow_tuple_element_aggregation, Tuple columns are flattened and
    their leaves summed, so a Tuple column is kept when any flattened leaf
    is summable (the whole physical column is read). The tuple recursion
    mirrors defineColumns' flattened-leaf gates: a *Map-suffixed array leaf
    is a summed-map candidate only when its synthesized parent is a real
    tuple ancestor and, with an explicit columns_to_sum, the leaf or an
    ancestor is named; otherwise the leaf is copied last-value and is not
    pinned (so an unlisted tuple *Map is not over-read).

Both read sites (spreadMarkRanges and getColumnsRequiredForMergingFinal,
which also feeds removeUnusedColumns) call one helper so they cannot diverge.

PREWHERE-before-FINAL: pinning the summing columns in the read set is not
enough on its own. PREWHERE column survival is decided by
StorageInMemoryMetadata::getColumnsRequiredForFinal() (the sorting key only),
so a PREWHERE touching only a subset of the summing columns strips the rest
before SummingSortedTransform, reintroducing the dropped-row bug (e.g.
SELECT c0 FROM s FINAL PREWHERE v_keep >= 0 ORDER BY c0 dropped the row whose
v_keep is non-zero but v_zero is zero). spreadMarkRangesAmongStreamsFinal now
restores the summing columns as PREWHERE outputs alongside the existing
sign/version/is_deleted restore, so they survive PREWHERE and reach the
transform. The zero-row decision itself is unchanged: genuinely all-zero
groups are still dropped.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-106125-summing-final-column-pruning branch from 3d7ddd4 to 31a56ee Compare July 9, 2026 11:32
@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 31a56ee

CI fully finished on this head. Every failure below has an owner. The only genuine test failures are one chronic trunk LOGICAL_ERROR (2 stress shards); the remaining reds are cancelled/superseded jobs (no test-level failure).

Check / test Reason Owner / fixing PR
Stress test (arm_debug / arm_tsan) — Not-ready Set is passed as the second argument (STID 0250) chronic trunk LOGICAL_ERROR (199 PRs / 27 master, 30d — not PR-caused) fixing PR #107924 (ours, open)
Build (arm_fuzzers), Build (loongarch64), Integration (amd_msan 6/8; amd_asan_ubsan db-disk old-analyzer 2/6, 5/6), Stateless (amd_tsan s3 seq 1/2; amd_llvm_coverage old-analyzer s3 DatabaseReplicated WasmEdge; arm_asan_ubsan targeted) cancelled / superseded (no test failure) re-run on next CI; no ownable failure
Report messages / Mergeable Check rollup of the above owned via #107924
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260709-163000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 84/87 (96.55%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6a9bb65

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky under parallel replicas (fresh trunk regression: 30d breadth is dozens of unrelated PRs plus master hits since 2026-07-28 20:15, so not caused by this PR) #112385 (mine, open)

Session id: cron:our-pr-ci-monitor:20260729-093000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@abashkeev abashkeev added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@PedroTadim

Copy link
Copy Markdown
Member

This PR is no longer needed.

@PedroTadim PedroTadim closed this Oct 12, 2026
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.

Wrong results: SummingMergeTree FINAL drops a present row when reading only a summation column that is 0 for it (read-in-order + column pruning)

6 participants