Skip to content

Fix missing rows when a projection present in only some parts is rejected - #124022

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/rejected-projection-keeps-parent-parts
Oct 11, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/rejected-projection-keeps-parent-parts

Conversation

@groeneai

@groeneai groeneai commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117394

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 some SELECT queries silently returning fewer rows when the table has a projection that exists only in some of its parts (for example, one added with ALTER TABLE ... ADD PROJECTION after data was inserted) and query_plan_remove_unused_columns is 0, which compatibility up to 25.11 sets.

Description

On 26.8.10.6 (also 26.3.33.24, 26.5, 26.6), with compatibility = '25.8', SELECT count() FROM (SELECT a FROM t WHERE b = 5) returns 10 instead of 20 when PROJECTION p (SELECT * ORDER BY b) was added after the first insert. The AST fuzzer hit the same defect as a NoREC mismatch on a commit_order projection (count 276 vs 308): job.log, on #117394.

optimizeUseNormalProjections removed the parts covered by the chosen projection from the table read (filterPartsByProjection) before its last bail-out: when the projection stream and the table stream have different headers (as with query_plan_remove_unused_columns = 0), it rejects the projection and returns, but the table read keeps the reduced part set, so those parts are read by nobody. The rejected projection was also reported in system.query_log.projections.

Now the part set is narrowed and the projection recorded only after the projection read is in the plan, so a rejection changes nothing. Which projection is chosen does not change: force_optimize_projection = 1 reports the same rejection.

The new test covers a regular projection, a commit_order projection with the fuzzer's _block_number filter, and the prefer_optimize_projection case of 03324_union_block_structure_mismatch. It fails on master in 50/50 randomized runs and passes in 50/50 with the fix, also with parallel replicas. The 302 other projection-related tests I ran give the same results before and after.

🤖 Generated with Claude Code


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

Version info

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

…cted

optimizeUseNormalProjections narrowed the parent ReadFromMergeTree to the
parts the chosen projection does not cover (filterPartsByProjection) and
recorded the projection in the query access info before the last point
where it can still give up: when the projection stream and the table
stream have different headers, the Union path rejects the projection and
returns. The projection read was discarded, but the parent read kept the
reduced part set, so the parts covered by the projection were read by
nobody, and system.query_log.projections named an unused projection.

The headers differ with query_plan_remove_unused_columns = 0, which
compatibility <= 25.11 sets: on 26.8.10.6,
SELECT count() FROM (SELECT a FROM t WHERE b = 5) returned 10 instead of
20 when PROJECTION p (SELECT * ORDER BY b) was added after the first
insert. The AST fuzzer found it as a NoREC mismatch on a commit_order
projection on PR ClickHouse#117394.

Compute has_parent_parts without mutating the parent analysis
(filterPartsByProjection keeps exactly the parts in parent_parts), and
narrow the parent read and record the projection only after the
projection read is wired into the plan, so a rejection has no side
effects. Which projection is chosen does not change.

Co-Authored-By: Claude Opus 5.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 Oct 5, 2026
@groeneai

groeneai commented Oct 5, 2026

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

Pre-publication review by an independent model (engine: codex; 1 finding).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test would also pass if the optimizer declined every projection; add an EXPLAIN projections = 1 check DISAGREE The contract is that a rejected projection loses no rows, which a declining optimizer also keeps. Every arm fails on master in 50/50 randomized runs, and master's query_log.projections names the rejected projection, so the path is exercised.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261005-115600

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A projection present in only some parts plus query_plan_remove_unused_columns = 0 (or compatibility <= '25.11'): SELECT count() FROM (SELECT a FROM t WHERE b = 5) returns 10 instead of 20 every time; also on official 26.3.33.24, 26.5.7.64, 26.6.8.7, 26.8.10.6.
b Root cause explained? optimizeUseNormalProjections called filterPartsByProjection on the table read's own analysis before its header-mismatch bail-out; on the bail-out the projection read is dropped but the table read keeps the reduced part set, so the covered parts are read by nobody.
c Fix matches root cause? Yes. The bail-out stays (it guards UnionStep header mismatches, 03324); the part filter and addQueryAccessInfo now run after the last return, so any rejection is side-effect free.
d Test intent preserved / new tests added? New 05325_normal_projection_rejected_keeps_parent_parts.sql: regular projection, commit_order projection with the fuzzer's _block_number filter, 03324's prefer_optimize_projection case, and system.query_log.projections.
e Both directions demonstrated? Master build: 50/50 randomized runs FAIL (16 vs 48, 10 vs 20, 1 row vs 2, rejected projection logged). Fix: 50/50 OK, plus 20/20 with parallel replicas for each parallel_replicas_local_plan value.
f Fix is general across code paths? optimizeUseAggregateProjections has no return after its filter and copies the analysis before other edits; the proof-based part drops in projectionsCommon.cpp are valid without the projection. Only this path was affected.
g Fix generalizes across inputs (params/datatypes/wrappers)? Plan-level control flow, type independent. Reproduced with ordinary, virtual-column and constant filters, regular and commit_order projections, the setting set directly and via compatibility.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; plans that use a projection are unchanged. Only a rejection now reads all parts and no longer lists the projection in query_log.projections.
i Invariants and contracts preserved? The table read loses parts only to a projection read that is in the plan. has_parent_parts keeps the same value at all four uses, and nothing between the old and new position reads the table read's part list. 302 projection-related tests unchanged.

Session id: cron:clickhouse-impl-slot-7:20261005-111506

@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4db04eb]

Summary: ✅


AI Review

Summary

This PR fixes optimizeUseNormalProjections so a rejected normal projection no longer leaves the parent ReadFromMergeTree narrowed to only the non-projected parts, which could silently drop rows and incorrectly record an unused projection in system.query_log.projections. The change defers both parent-part filtering and projection access logging until after the projection path is successfully wired into the plan, and the new stateless regression test covers the row-loss and query_log regressions. I did not find a correctness, safety, or PR-metadata issue in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 4db04eb.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.60% 79.70% +0.10%

Changed lines: Changed C/C++ lines covered: 21/21 (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 Oct 5, 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 Oct 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4db04ebb6 with master 9357b9bdb (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

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

Job report

@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
Merged via the queue into ClickHouse:master with commit 5a45502 Oct 11, 2026
149 of 150 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 11, 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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants