Skip to content

Fix the missing WITH TOTALS row of a JOIN whose ON is constant false - #124134

Merged
nickitat merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-constant-false-join-totals
Nov 6, 2026
Merged

nickitat merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-constant-false-join-totals

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123702
Related: #110234

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 a missing or wrong WITH TOTALS row of a JOIN whose ON condition is constant false when an input that the join does not need to read produces totals. Appeared in 26.8 with query_plan_short_circuit_constant_false_join.

Description

On 26.8.18.2, this query returns no totals row instead of 0 0 6 (the same query with query_plan_short_circuit_constant_false_join = 0, or on 26.7):

SELECT * FROM (SELECT number % 2 AS k FROM numbers(4)) AS l
LEFT JOIN (SELECT number % 3 AS k, count() AS c FROM numbers(6) GROUP BY k WITH TOTALS) AS r ON l.k = r.k AND 1 = 2
ORDER BY ALL;

With totals on both inputs the totals row is 0 45 0 0 instead of 0 45 0 6.

The constant-false ON short-circuit (#110234) replaces an input that the join kind does not preserve with ReadNothing. No row of that input reaches the output, but the join builds its totals row from the totals of both inputs, and ReadNothing has none.

The pass now keeps an input whose plan can produce totals: a TotalsHaving step, a remote read whose shard query has WITH TOTALS, a query result cache hit with totals, the same inside a nested plan (a SQL SECURITY DEFINER view), or a Merge table (its child plans are not built here). It does not look below an aggregation, which drops the totals of its input. Everything else keeps the fast path.

The new test covers LEFT, RIGHT, INNER, both inputs with totals, an aggregation over a WITH TOTALS subquery, remote() with and without totals, a sealed view, merge() and the query result cache; the expected output is the output of the same queries with the setting off.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1567-master (included in 26.11 and later)

groeneai and others added 2 commits October 6, 2026 02:20
The constant-false ON short-circuit (ClickHouse#110234) replaces every input the join
kind does not preserve with ReadNothing. No row of such an input reaches the
output, but the join builds its totals row from the totals of both inputs
(joinPipelinesRightLeft), and that stream does not go through ON. So a
`WITH TOTALS` input lost its totals row (or got defaults for it) since 26.8.

The pass now keeps an input whose plan can produce totals: TotalsHavingStep,
ReadFromRemote whose shards send totals (stage Complete and a WITH TOTALS
shard query, the predicate addPipe/addLazyPipe already used, now one helper),
a query result cache hit whose pipe has totals, any of these in a nested plan
the step owns (a SQL SECURITY DEFINER view), and ReadFromMerge, whose child
plans are built on request and so are not inspected here. The walk stops
below AggregatingStep and MergingAggregatedStep, which drop incoming totals,
and does not ask LazyReadReplacingFinalStep (one source, no totals). Inputs
without totals keep the fast path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove the obvious doc comment on ReadFromRemote::hasTotals.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Oct 6, 2026
@groeneai

groeneai commented Oct 6, 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; 2 findings; 1 full pass).

# Sev Finding Verdict Evidence / action
1 ⚠️ 05331 does not pin join_use_nulls, so a stress worker with join_use_nulls=1 prints NULL instead of 0 DISAGREE Only ci/jobs/scripts/stress/stress.py:410-411 sets it, and the stress job does not compare test output with references (its results are server-level rows only); clickhouse-test does not randomize it.
2 ⚠️ With a session-wide use_query_cache=1 the second cache run can be a top-level hit, so the arm passes without the join DISAGREE Only stress.py:448-450 sets it (same as above). In the jobs that check references, removing the cache clause from canProduceTotals turns exactly that arm red.
3 💡 A Merge input is always read under a constant-false ON, since its child plans are not built here AGREE, no change Intended and mentioned in the description; rare shape.

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

Session id: cron:clickhouse-review-slot-49:20261006-022300

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: the LEFT JOIN query in the description prints no totals row on every run at default settings (master 7360ed8, official 26.8.18.2).
b Root cause explained? The constant-false ON short-circuit replaces a non-preserved input with ReadNothing; the join builds its totals row from both inputs' totals, which do not go through ON, and ReadNothing has no totals port.
c Fix matches root cause? Yes: the pass no longer replaces an input whose plan can produce totals; the other input keeps the fast path.
d Test intent preserved / new tests added? New 05331_short_circuit_constant_false_join_totals; 04512_short_circuit_constant_false_join unchanged and green.
e Both directions demonstrated? [ OK ] with the fix, [ FAIL ] on master with every totals row missing; each of the 7 detection clauses, when removed, turns its own arm red. 50/50 randomized runs green.
f Fix is general across code paths? One check in the shared per-side helper covers both sides of every join kind; it detects every plan-level totals producer (TotalsHaving, remote with WITH TOTALS, query cache, nested plans, Merge).
g Fix generalizes across inputs (params/datatypes/wrappers)? Totals on either or both inputs, through remote(), a sealed view, merge() and the query cache; an aggregation over WITH TOTALS keeps the fast path. Detection is structural, so types do not matter.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change; affected queries return what they returned before 26.8 and with the setting off.
i Invariants and contracts preserved? add_totals in ReadFromRemote is computed by the same predicate as before (now one helper); the walk only reads the plan; the cache step's pipe is read before pipeline building consumes it.

Session id: cron:clickhouse-impl-slot-5:20261006-012400

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5574c65]

Summary: ✅


AI Review

Summary

The PR preserves WITH TOTALS when a constant-false JOIN would otherwise discard an input that supplies totals. No actionable findings at 5574c65c5ab9c132e176d7bf312c249165cdc7f7. All 13 local comparisons using the PR's fast-test binary returned identical rows and totals with the optimization enabled and disabled, including nested joins, aggregation boundaries, UNION ALL, sealed views, and Merge.

Missing context / blind spots
  • ⚠️ The CI workflow is still running. Remote reads and query-cache execution were reviewed in code but were not rerun locally; completion of the added stateless regression test would close this validation gap.
Final Verdict

Status: ✅ Approve. No code changes requested; await the remaining CI results.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 6, 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 6, 2026
@nickitat nickitat self-assigned this Oct 8, 2026
…join-totals

# Conflicts:
#	src/Processors/QueryPlan/ReadFromRemote.h
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5574c65c5 with master b51e7acfe (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 86abc2f7f; 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.

Object file sizes

5 object files changed (+24.31 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/shortCircuitConstantFalseJoin.cpp.o 18.82 KiB 42.56 KiB +23.75 KiB (+126.20%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Translation unit Master PR Δ vs median
src/Processors/QueryPlan/Optimizations/shortCircuitConstantFalseJoin.cpp 4.1 s 11.7 s +7.7 s (+191%)

Job report

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 5, 2026
…ult has totals

On a subquery query cache hit, the Planner replaces the subquery plan, its
`TotalsHaving` included, with a `ReadFromQueryResultCacheStep` whose pipe has a
totals port when the cached entry has totals. `canProduceTotals` only knew
`TotalsHavingStep` and the remote reads, so lazy materialization over joins was
applied and the cached totals block reached the expression above the `LIMIT`
without the lazily read column: the second run of a `LEFT JOIN` of a cached
`WITH TOTALS` subquery threw NOT_FOUND_COLUMN_IN_BLOCK, while the first run (a
miss, which still has `TotalsHaving` in the plan) was correct.

Count a cache read whose pipe has totals as a totals source. A cache hit without
totals keeps lazy materialization. The `hasTotals()` accessor is the same line
as in ClickHouse#124134, which needs it for the constant-false join shortcut.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nickitat
nickitat enabled auto-merge November 6, 2026 20:18
@nickitat
nickitat added this pull request to the merge queue Nov 6, 2026
Merged via the queue into ClickHouse:master with commit 52429b7 Nov 6, 2026
185 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 Nov 6, 2026
alexey-milovidov pushed a commit that referenced this pull request Nov 14, 2026
26.10 does not include Formats/FormatSettings.h in StorageView.cpp, and
does not have the GRANTs of #123729 in 05257_sql_security_view_sealed.sh,
so only this PR's lines are added there. The test
05331_short_circuit_constant_false_join_totals (#124134) is not on 26.10,
so this PR's change to it is dropped.

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

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-review-human PR origin: human review feedback on a groeneai PR 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