Skip to content

Do not leak a correlated subquery's TOTALS into the outer query - #107075

Open
groeneai wants to merge 19 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-correlated-subquery-with-totals-106920
Open

groeneai wants to merge 19 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-correlated-subquery-with-totals-106920

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 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):

Fixes a spurious TOTALS block returned for a non-aggregate SELECT whose WHERE contains a correlated subquery using GROUP BY ... WITH TOTALS. The subquery's totals are no longer propagated as the outer query's totals.

Description

Closes: #106920

A non-aggregate SELECT returned an extra totals row when its WHERE contained a correlated scalar or EXISTS subquery producing a totals stream:

CREATE TABLE t (id UInt32, val Int64) ENGINE = MergeTree ORDER BY id;
INSERT INTO t SELECT number, number * 7 FROM numbers(3);
SELECT id FROM t WHERE id >= (SELECT 0 GROUP BY 1 WITH TOTALS HAVING isNull(val) = 0);
-- returned 0, 1, 2 and then a spurious totals row

Root cause. A subquery's totals are not part of the value it returns; the non-correlated scalar evaluator consumes data chunks only. Decorrelation replaces the subquery with a JOIN, and joinPipelinesRightLeft propagates totals from whichever input has them.

The change. buildLogicalJoin is the only place where the join's two inputs are unambiguous, so it records there which input carries the subquery (after the correlated_subqueries_default_join_kind swap, so one expression covers both values). JoinStep::updatePipeline drops that input's totals and extremes at the top, before the swap_streams swap and before algorithm dispatch, the only point where the pipelines still match the step's declared inputs. Only the carrier input is touched, so a legitimate totals stream on the other input still propagates (guarded by 03808_correlated_subquery_with_totals).

That side is only meaningful while the join has two inputs, so the existing swap-only query_graph_size_limit = 2 clamp is extended to cover it, and the side is re-derived after reconstruction, reversing it when the optimizer flips the children.

Validation. New test 04327_correlated_subquery_with_totals, 26 assertions covering scalar and EXISTS, nested totals, both values of correlated_subqueries_default_join_kind and correlated_subqueries_use_in_memory_buffer, an aggregating outer query, extremes = 1, WITH ROLLUP, a cached subquery, a distributed plan. Fails on master, passes here, 50 randomized runs green. The existing correlated suite shows no reference churn: the only .reference this PR changes is the new one.


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

A top-level SELECT with no aggregation returned a spurious totals block to
the client when its WHERE contained a correlated scalar or EXISTS subquery
whose plan produced a totals stream (GROUP BY ... WITH TOTALS).

Correlated-subquery decorrelation rewrites the subquery into a JOIN. JoinStep
propagates totals from either input, so a totals stream produced by the
subquery (a TotalsHavingStep not consumed by an enclosing aggregation, which
would drop it) leaked through the decorrelation join into the outer
non-aggregate pipeline and reached the client as a totals row of the outer
query.

Detect such a surviving totals stream in the correlated subquery plan and
reject decorrelation with NOT_IMPLEMENTED, for both the scalar and EXISTS
paths. A nested WITH TOTALS consumed by an enclosing aggregation, as well as
WITH ROLLUP/CUBE, are unaffected and keep working.

Closes: ClickHouse#106920

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On master HEAD, SELECT id FROM t WHERE id >= (SELECT 0 GROUP BY 1 WITH TOTALS HAVING isNull(val) = 0) deterministically returns 0,1,2 plus a spurious totals row (JSONCompact shows "totals":[0]). Also reproduces via EXISTS (...) and via a nested non-aggregated WITH TOTALS (e.g. (SELECT x FROM (SELECT 0 AS x GROUP BY 1 WITH TOTALS) AS s WHERE t.val >= 0)).
b Root cause explained? Correlated-subquery decorrelation rewrites the subquery into a JOIN. JoinStep::transformPipeline propagates totals from either input (addDefaultTotals), so a totals stream produced by the subquery (a TotalsHavingStep not consumed by an enclosing AggregatingStep, which would drop it via dropTotalsAndExtremes) flows through the decorrelation join into the outer non-aggregate pipeline and reaches the client as a totals row of the outer query. The existing decorrelateQueryPlan "step not supported" throw only fires when the TotalsHaving step is itself correlated; in the common case it sits in a non-correlated subplan that is wrapped wholesale, so it was never rejected.
c Fix matches root cause? Yes. Before decorrelating, the plan is walked from the result down; if a TotalsHavingStep is reachable without crossing an AggregatingStep, decorrelation is rejected with NOT_IMPLEMENTED (for both the scalar and EXISTS paths). This targets exactly the surviving-totals-stream mechanism, not a symptom.
d Test intent preserved / new tests added? New regression test 04327_correlated_subquery_with_totals added. It asserts the three leaking shapes (scalar, EXISTS, nested) now error with NOT_IMPLEMENTED, and asserts the safe shapes still return correct rows: a nested WITH TOTALS consumed by an enclosing max(), WITH ROLLUP, and the same shape without WITH TOTALS. No existing test was weakened; all 16 existing *correlated* tests pass.
e Both directions demonstrated? Yes. Without the fix the queries return the spurious totals; with the fix they error with Code: 48 NOT_IMPLEMENTED, while the safe queries return their expected rows. The new test was run through clickhouse-test and passes; the relevant decorrelation settings (both prewhere flags off, correlated_subqueries_default_join_kind LEFT/RIGHT, in-memory buffer, two-level aggregation, equivalence-class substitution) all consistently produce the rejection.
f Fix is general, not a narrow patch? Yes. The detection is applied to both correlated-subquery kinds (SCALAR and EXISTS) and is plan-structural (handles top-level WITH TOTALS, HAVING-correlated WITH TOTALS, and nested non-consumed WITH TOTALS alike), rather than matching a single AST shape. It is not a defensive guard at the leak site: it stops decorrelation at the point the unsupported totals stream is detected.

Session id: cron:clickhouse-worker-slot-2:20260610-193654

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vdimir — could you review this? It fixes #106920: a correlated scalar/EXISTS subquery using GROUP BY ... WITH TOTALS leaked its totals stream through the decorrelation JOIN into the outer non-aggregate query (spurious TOTALS row). The fix detects a TotalsHavingStep reachable in the subquery plan without an enclosing AggregatingStep and rejects decorrelation with NOT_IMPLEMENTED, for both the scalar and EXISTS paths; nested totals consumed by an aggregation, and ROLLUP/CUBE, are unaffected.

@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8b6d9dc]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) FAIL
03312_squashing_with_low_card_mem_usage FAIL cidb

AI Review

Summary

This PR fixes leaked subquery TOTALS / extremes for decorrelated correlated subqueries by recording which join input carries the subquery and dropping that input's auxiliary streams in JoinStep. The local, cache, distributed-plan, and join-order paths look well covered, but the new marker is not preserved when the decorrelation join is shipped as a serializable fragment, so the original leak can reappear under plan-based parallel replicas.

Findings

❌ Blockers
[src/Processors/QueryPlan/JoinStepLogical.h:235] decorrelated_subquery_side is explicitly documented as runtime-only, but under correlated_subqueries_use_in_memory_buffer = 0 the second optimization pass materializes CommonSubplanReferenceStep and removes CommonSubplanStep, which leaves the decorrelation join fully serializable. applyParallelReplicas::liftSplitAboveJoin can then ship that LEFT/RIGHT ANY join as a remote fragment, while JoinStepLogical::serialize drops the side marker. The replica-side JoinStep therefore sees nullopt and stops removing the subquery input's TOTALS / extremes, recreating the original wrong-result bug on shipped fragments.
Suggested fix: serialize and deserialize decorrelated_subquery_side, or fail closed by making marked decorrelation joins non-serializable / non-shippable until the marker can survive remote execution.

Tests

⚠️ Add a focused regression for plan-based parallel replicas with correlated_subqueries_use_in_memory_buffer = 0 and a correlated subquery that produces TOTALS (and ideally extremes = 1). The current suite exercises local execution, query-cache replay, distributed-plan routing, and join-order flips, but not the shipped-fragment path that loses this marker.

Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.90% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 84/85 (98.82%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on cac5b03fba62: 51 checks pass. The single non-passing functional check is infrastructure, not a test failure:

  • Stateless tests (amd_asan_ubsan, distributed plan, parallel, 1/2) — conclusion = CANCELLED after running 6h0m15s (hit the job time limit). CIDB recorded zero FAIL/ERROR test rows for this shard. The sibling 2/2 shard ran the same settings and succeeded. This is a runner timeout on a heavily-contended asan job, unrelated to this Planner-only change (correlated-subquery WITH TOTALS decorrelation rejection). A re-run should clear it.

The remaining red marks (Mergeable Check, PR, CH Inc sync) are derivative aggregators of the cancelled shard. No PR-caused failure.

Session: cron:our-pr-ci-monitor:20260611-120000

@qoega

qoega commented Jun 17, 2026

Copy link
Copy Markdown
Member

@groeneai update branch and make CI green

@groeneai

Copy link
Copy Markdown
Collaborator Author

Done. Merged current master into the branch; HEAD is now 384d624b36162504cc1c54ba567bc152f4c2acc9.

The merge is clean (no conflicts) and src/Planner/PlannerCorrelatedSubqueries.cpp was untouched by master, so the fix is unchanged. Rebuilt locally and re-verified: the scalar repro, the EXISTS variant, and the nested unconsumed-totals case all reject with Code: 48 NOT_IMPLEMENTED; the allowed shapes (max() over nested WITH TOTALS, WITH ROLLUP, and the no-totals shape) still return 0,1,2.

CI is re-running on the new commit. The only non-pass on the prior run was a cancelled asan stateless shard (6h runner timeout, zero failed test rows), which the fresh run should clear. May need a maintainer to approve the workflow run for the fork branch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI re-ran on the updated branch (HEAD 384d624b). No PR-caused failures. The two non-green checks are CI infrastructure, unrelated to this Planner-only change (src/Planner/PlannerCorrelatedSubqueries.cpp):

Session: cron:our-pr-ci-monitor:20260617-193000

groeneai and others added 8 commits July 29, 2026 19:03
…ing the query

A correlated subquery's own totals are not part of its value: the non-correlated scalar path
consumes data chunks only, so `SELECT number FROM numbers(3) WHERE number >= (SELECT 0 GROUP BY 1
WITH TOTALS)` already returns no totals. Decorrelation replaces the subquery with a join, and a
join propagates totals from either input, so the subquery's totals became the outer query's totals
and reached the client as a spurious totals row.

Drop those streams on the subquery plan just before the decorrelation join is built, for both the
scalar and the EXISTS kind, and remove the NOT_IMPLEMENTED guard this branch added earlier. The
guard inspected only the subquery plan, so it also rejected `SELECT count() ... WITH TOTALS ...`,
which master answers correctly because the outer aggregation drops the totals itself.

The step is added unconditionally: the transform is a no-op without those streams, so nothing has
to recognize which step produced them. That also covers a warm query result cache, which replaces
the subquery plan with a step carrying the cached totals and no TotalsHavingStep.

The step implements the query plan serialization contract, because a distributed plan serializes
every step of every fragment.

NOT READY TO PUBLISH: this perturbs the join-order optimizer. Under
query_plan_optimize_join_order_algorithm = 'dpsize' or 'dphyp' a query that master answers
correctly now fails with EXPERIMENTAL_FEATURE_ERROR, because the optimizers locate their operands
with a single-hop exact-type typeid_cast on a node's direct child. See
.scratch/impl-findings-r1.md; committed so the planning phase can inspect the implementation.
…es it

The previous commit inserted a DropTotalsAndExtremes plan step into the
decorrelated subquery plan. That works for the reported bug but breaks the join
order optimizer: the plan optimizers locate their operands with exact-type,
single-hop typeid_cast on a join's direct child, so an extra step between a join
and its input hides the operand. A query that master answers correctly then
fails outright with Code: 717 EXPERIMENTAL_FEATURE_ERROR under the dpsize and
dphyp join-order algorithms, and five correlated-subquery EXPLAIN references
move.

Do it without adding any plan node. The decorrelation result join is the only
place where the two inputs are known unambiguously (the subquery plan and the
outer input stream, swapped only by correlated_subqueries_default_join_kind), so
record there which input carries the subquery, and have the physical join drop
that input's totals and extremes at the top of updatePipeline, before the
swap_streams swap and before algorithm dispatch. The drop reuses the existing
DroppingTransform-based helper rather than Pipe::dropTotals, whose childless
NullSink would let ExecutingGraph::initializeExecution seed a gated source
sub-pipeline early.

The recorded side is only meaningful while the join still has two inputs, so
extend the existing query_graph_size_limit = 2 clamp to cover a marked join and
re-derive the side after reconstruction, which also reverses it when the
optimizer flips the two children. The join is created ANY, for which
isSwapOnlyJoinStrictness is already true, so that clamp already fires for every
totals-carrying shape; the added disjunct keeps it firing after
tryConvertAnyOuterJoinToInnerJoin rewrites the strictness to ALL. The
child-side flatten gates get the same check because they run with an enclosing
join's limit rather than the marked join's.

The NOT_IMPLEMENTED guard removal from the previous commit stays: refusing the
query rejected correct aggregating outer queries such as SELECT count().

No serialization contract is added. A plan retaining a TotalsHaving step is
never distributed, and a WITH TOTALS correlated subquery is refused earlier by
decorrelateQueryPlan, so the policy needs no round trip.

Since no plan node is added, no plan text moves: all five references the
previous approach churned pass unmodified, and the r1 Code: 717 regression is
gone under all three join-order algorithms.

Also pin parallel replicas off on the test's distributed-plan statement.
make_distributed_plan rejects them with SUPPORT_IS_DISABLED and the test runner
randomizes them on, which failed 15 of 50 randomized runs.
…d say what really keeps the marker safe

Review round 1 raised three points about the contract around the fix, not the fix
itself.

The comment on decorrelated_subquery_side claimed the member is never serialized
because "a plan retaining a TotalsHaving step is never distributed". An
instrumented build refutes the conclusion: a marked join does reach
JoinStepLogical::serialize, on the very shape the test's distributed row uses
(make_distributed_plan, correlated subquery, no WITH TOTALS). Correctness is
unaffected, but for a different reason than the comment gave. The shapes that
reach serialization are exactly the ones with no totals to drop: with
make_distributed_plan a totals-carrying plan is refused up front by
planHasUnsupportedDistributedStep, and with serialize_query_plan and parallel
replicas findQueryForParallelReplicas declines a decorrelated join tree so
nothing is serialized at all. Measured with a positive control on the same
server: the non-correlated twin of the same query dispatches three secondary
queries, every correlated arm dispatches none. The comment now names the
enforcing mechanism per route. No serialization format change: encoding the side
would guard a state that cannot exist.

The final query-cache row exercised the only cached correlated subquery in the
test, but the rows it reads had been restored just above, so it returned the same
result whether the cache was used or not. It was in fact hitting the cache
(QueryCacheHits = 1, measured per statement), the test just could not prove it.
It now carries a log_comment and asserts the hit, which reddens both when reads
are disabled and when one hashed setting is perturbed.

The distributed row likewise had no oracle that the route ran, so it would have
degraded to a plain local query in silence if make_distributed_plan ever stopped
accepting the shape. It now asserts that the plan contains an Exchange step,
which is present only in a distributed plan. Step names are printed by every
EXPLAIN mode, so the assertion does not depend on explain_query_plan_default.

Also state the ordering ground for the join-order clamp: the conversion to
ALL/INNER happens in the first-pass optimization array while the clamp runs in
the second pass, so a marked join can arrive already converted.

The lightweight_deletes_sync pin on the delete is documentation of what the
following row depends on. Its default is already 2 and nothing in the test
harness can change it, so it is not load-bearing.
Review round 2 findings, both test-side. No production logic changes; the one
src/ edit is a comment clause.

The carrier side is re-derived after join-order reconstruction, but nothing in
the suite reached the flip path: every totals shape produced left_rels=1,
right_rels=1 with no flip, so transporting the recorded side without reversing
it broke nothing. Forcing query_plan_join_swap_table = true reaches it, and the
new arm then leaks a totals block under that mutation because the drop lands on
the outer input. The functional runner deliberately never injects true, but the
stress runner does. The order limit is pinned alongside it: at 0,
optimizeJoinLogicalImpl returns before chooseJoinOrder runs, so the flip cannot
happen and the arm would silently duplicate the row above it. The runner draws 0
with 5% probability.

The query result cache is a server-wide resource, and TTLCachePolicy::set
declines a write outright when the cache holds too many live entries rather than
evicting one, which can fail the rows asserting the warm entry and the cache
hit. Every cache statement now carries query_cache_tag = '04327_totals', which
is folded into the entry key, so a concurrent test running the same subquery
cannot occupy our key. The tagged drop before the warm write reclaims the slots
our own prior entries hold; measured on a cache filled to its 1024-entry limit
with our tag, the test passes with the drop and fails without it. Note the tag
predicate only removes keys whose tag matches, so unlike an untagged
SYSTEM DROP QUERY CACHE this leaves every other test's entries in place.
Verified: with the cache full of foreign tags, no other test's entry is
touched.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tion contract per route

Two review findings, both about the round's non-functional halves. No behaviour change.

The query cache is a server-global resource and TTLCachePolicy::set declines a write
outright when the cache is full of live entries rather than evicting to make room, so the
three rows that need our entry to exist could fail whenever a concurrent test has filled
the cache. A per-tag drop cannot help: it removes entries carrying the tag, while the
constraint is capacity, which no tag, key or database can scope. The test therefore drops
the whole cache and is tagged no-parallel, matching what every other query-cache test in
the tree does, and cleans up after itself. query_cache_tag stays, because it still keys the
entry distinctly and keeps the system.query_cache assertion specific. The reference does not
move; disabling cache reads on the cache-hit statement still flips that one assertion, so
the block is no less discriminating than before.

The comment on decorrelated_subquery_side claimed that the only plans reaching serialize
are ones with no totals to drop. That absolute claim was wrong: two more serialization
routes exist. It now names each route and the mechanism that enforces correctness there.
The route reached through serialize_query_plan was measured with an instrumented probe:
a correlated subquery cannot coexist with a remote table at all, which
validateCorrelatedSubqueries refuses during analysis, before any plan is built, so no
marked join is ever created on that route. Nothing is encoded into the serialized form,
because there is no state to preserve.
…query_side

The doc comment above `decorrelated_subquery_side` claimed that every route
which can serialize a plan enforces what the member provides "by its own
mechanism", then enumerated four routes. The enumeration was unbounded by
construction and had rotted four times: it breaks when a new route appears and
also when a new step type appears inside an existing route.

The latter is what happened for the query result cache. A warm cache entry
replaces the subquery plan with `ReadFromQueryResultCacheStep`, whose totals
arrive as a pipe source, so the plan contains no `TotalsHavingStep` at all and
`planHasUnsupportedDistributedStep` (which tests exactly four step types) does
not recognize it. The header credited that check with covering the route, which
contradicted this change's own test file, where the cached shape is exercised
precisely because it "contains no TotalsHavingStep, so a check that recognized
step types could be defeated by it".

State the invariant that actually holds for every route instead: a decorrelated
plan always contains steps that are not serializable, so it cannot cross a
serialization boundary unrefused. `CommonSubplanStep` and
`CommonSubplanReferenceStep` are added by decorrelation unconditionally, a
cached subquery adds `ReadFromQueryResultCacheStep`, and none of them override
the `IQueryPlanStep::isSerializable` default of `false`; therefore
`assertFragmentSerializable` rejects the fragment and `IQueryPlanStep::serialize`
throws. A future step that would carry the subquery's totals across a boundary
has to opt into serialization explicitly, which is exactly the point at which
this member would have to be serialized too.

The four routes are kept as illustrative examples, explicitly not as an
exhaustive list, and the `make_distributed_plan` entry now states both halves:
the unsupported-step scan catches a `TotalsHavingStep`-carrying plan, while a
cached totals stream is caught by the fail-closed check instead.

Comment only. Executable code is byte-identical: stripping debug info from the
recompiled object yields the same bytes as building it from the previous
header, so the Build ID moves only because the member's DWARF decl_line shifts.
…ation

The comment claimed a marked join cannot reach a serialization boundary
unrefused, and attributed the refusal to a fail-closed serializability check.
Both halves were wrong.

The named steps are absent at both values of
correlated_subqueries_use_in_memory_buffer: at the default the plan carries the
buffer steps instead, and in the other arm CommonSubplanStep and
CommonSubplanReferenceStep are removed before anything serialization-related
runs, leaving a plan whose every step (including the marked join itself) is
serializable. Separately, assertFragmentSerializable has a single call site,
inside the multi-stage branch of QueryPlan::convertToDistributed, so it is
make_distributed_plan machinery and cannot carry a route-independent claim.

State only what is measured: the member is runtime-only because
JoinStepLogical::serialize does not write it, and on the routes exercised so far
a totals-carrying decorrelated plan is refused before any serialization
boundary, each route for its own reason. Keep the route examples, which are
accurate, and drop route 1's reference to the withdrawn check. Where a refusal
is not established, for a cached subquery whose totals stream carries no
TotalsHavingStep, say so rather than name a mechanism.

Comment only. Every changed line is a comment and .text is byte-identical to
the previous build; the Build ID moves only because the block is one line
shorter, which shifts debug line info.
The summary above `decorrelated_subquery_side` claimed every route that could
carry the subquery's totals is "refused before it reaches a serialization
boundary", but two of the bullets under it described something else: a
set-subquery plan IS serialized and is harmless only because the consumer drops
the streams itself, and the `make_distributed_plan` bullet explicitly declined
to claim a refusal for the cached-totals shape. A reader who trusted the
summary and then read the bullets found them contradictory.

State the two distinct properties instead of generalizing one word over both,
and say plainly that neither is a general proof. The cached-plan bullet no
longer ends in an open question: `ReadFromQueryResultCacheStep` derives from
`ReadFromPreparedSource` and overrides neither `isSerializable` nor
`serialize`, so it inherits the `IQueryPlanStep::isSerializable` default and
`assertFragmentSerializable` rejects the fragment before execution; it is also
absent from `QueryPlanStepRegistry`, so serialization would throw
`NOT_IMPLEMENTED` independently. Also record once, in the summary, the
direction a reader actually needs: losing the marker can only lose a drop, it
can never move one to the wrong input.

The parallel-replicas bullet is dropped rather than reworded a fifth time. It
was the weakest of the four, since declining a plan whose non-join steps are
unsupported is not the same as declining a decorrelated join tree, and it is
not needed once the two properties are stated.

Comment-only. Object code is unchanged: rebuilt against a control arm with the
previous comment restored, both binaries have a byte-identical `.text`
(750918432 bytes, sha256 0a2f9eead1995845...). The Build ID differs only
because the block grew by one line, which shifts DWARF line tables.
@groeneai groeneai changed the title Reject decorrelation of correlated subqueries with WITH TOTALS Do not leak a correlated subquery's TOTALS into the outer query Jul 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review, final round (clean: 0 findings from the reviewing model, 8 findings adjudicated)

I ran a cold independent review of the resulting code and a second-model review pass, then
adjudicated every finding against the source. This is the last of 6 fix rounds; 9 second-model
passes raised 17 findings in total, and the final pass on this content returned none.

My own cold review found no blockers and no majors. I enumerated the invariant carriers
independently before comparing them with the plan, and the two lists matched: of the nine sites
that inspect a child JoinStepLogical in optimizeJoin.cpp, exactly the two that flatten a child
into extra relations carry the new guard, and the three constructors that can preserve the marker
(clone, the join-order reconstruction, deserialize) are each accounted for.

❌ Agreed, fixed in this round

# Finding Verdict
1 The validation paragraph gave an exact size for the correlated test suite, which read as a claim about the resulting tree while the number came from the pre-existing one. Agreed. Both numbers were individually true with different denominators, which is exactly why the sentence was wrong. The count is removed; the churn statement that remains is denominator-independent and directly checkable from the diff.

⚠️ Adjudicated, no change

  • Whether to keep the graph-size clamp's new disjunct. The implementation measured that it is
    not load-bearing today and asked for a decision. The measurement is right, and I found the
    mechanism: the ANY to ALL join conversion requires an aggregating step as the direct child of
    the side it inspects, while a totals-carrying decorrelated plan has a TotalsHaving step above
    that aggregation, so the conversion declines and every totals-carrying join still arrives with a
    strictness the pre-existing clamp already covers. Kept anyway: without it, the marker's safety
    would rest on a pass in a different file never accepting such a side, which no test can pin
    because those joins are clamped regardless. Removing it would also mean removing the two
    child-side guards, which protect a different boundary.

  • The length of the comment documenting the deliberately unserialized member. It exceeds the
    target the fix plan set, and the plan's own content requirements sum to the length shipped. Kept
    as written rather than dropping the enumerated serialization routes: each route is a separately
    verifiable claim and I verified all four, and a reader without them cannot check the argument at
    all. Comparable blocks in the same subsystem run longer.

  • Two observations I raised and then withdrew myself. The filled-join construction path drops
    the marker, but is unreachable for a decorrelation join and structurally cannot express a
    two-sided drop; and three of the four join pipeline builders refuse totals outright rather than
    propagating them, which confirms the chosen placement rather than revealing a gap.

💡 Noted, not blocking

Two items the implementation reported instead of working around: a prescribed liveness proof for one
test row does not hold on the build it named (the plan-output tests carry that claim instead), and a
further prescribed row is not expressible because the shape is refused earlier during decorrelation.
The shipped test already pins that earlier refusal, so no coverage is lost. Both were correct to
report rather than to substitute silently.

Session id: cron:clickhouse-review-slot-48:20260730-230500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Answer
a Deterministic repro? Yes. SELECT id FROM t WHERE id >= (SELECT 0 GROUP BY 1 WITH TOTALS HAVING isNull(val) = 0) FORMAT JSONCompact prints a "totals" field on every run on master and never after the fix.
b Root cause explained? A subquery's totals are not part of the value it returns; the non-correlated scalar evaluator consumes data chunks only. Decorrelation replaces the subquery with a JOIN, and joinPipelinesRightLeft propagates totals from whichever input has them, so they become the outer query's totals.
c Fix matches root cause? The streams are dropped at the join that consumes them, on the carrier input only. No widened bound, no no-random-* tag, no reduced dataset, no defensive check masking an upstream bug.
d Test intent preserved / new tests? New test with 26 assertions, including must-not-change controls: an aggregating outer query, the outer query's own extremes, WITH ROLLUP, a totals-consuming aggregate, and the pre-existing serverError NOT_IMPLEMENTED for a correlated TotalsHaving step. Every existing correlated test passes unmodified.
e Demonstrated in both directions? Fails on master with 9 spurious totals blocks; passes with the fix. 15 mutations were run: not setting the policy, not consuming it, inverting the recorded side, hard-coding it, and suppressing on every join each redden the suite; the side inversion also reddens 03808_correlated_subquery_with_totals, which is what proves the guard is side-aware rather than blanket. Each of the two new oracles is separately proven discriminating: disabling cache reads, or perturbing one hashed setting, turns the cache-hit assertion from 1 to 0 while the main rows stay identical, and removing make_distributed_plan turns the distributed-route assertion from 1 to 0. The reversal that re-derives the carrier side after the optimizer flips the join's children is covered by pinning query_plan_join_swap_table = true on one statement: EXPLAIN confirms the flip moves both the join kind and the child order, and transporting the recorded side without re-deriving it makes that statement leak a totals block while every other row stays green.
f General across code paths? The drop happens at the physical join, so all three join pipeline routes are covered by construction. Both decorrelation branches (scalar and EXISTS) go through the same buildLogicalJoin and are both asserted. LogicalJoinInfo is the only logical-to-physical channel, verified tree-wide. The sibling inner CROSS join is deliberately not marked, and a mutation marking it too changes nothing.
g Generalizes across inputs? Both values of correlated_subqueries_default_join_kind and of correlated_subqueries_use_in_memory_buffer; scalar and EXISTS; a nested subquery; a query-cache-served subquery that carries no TotalsHavingStep; an aggregating outer query; a distributed plan; extremes = 1; WITH ROLLUP.
h Backward compatible? No setting default changed, no new setting, no serialization or on-disk format change, so no SettingsChangesHistory.cpp entry is owed. The new member is in-process only, and an instrumented build measured what happens when it is dropped by serialization: the shapes that reach plan serialization are exactly those with no totals to drop, because a totals-carrying decorrelated join is refused before any pipeline exists.
i Invariants and contracts preserved? The drop runs before the swap_streams swap and before algorithm dispatch, the only point where the pipelines still correspond to the step's declared inputs; a mutation moving it after the swap was run and reported. The primitive is the existing DroppingTransform wrapper rather than Pipe::dropTotals, so no childless NullSink is added and ExecutingGraph::initializeExecution cannot seed a gated source sub-pipeline early. Dropping the input's extremes costs nothing because all three join routes already drop both inputs' extremes and the outer extremes are produced later by addExtremesStepIfNeeded, which the extremes = 1 row asserts.

Randomized runs: 50 of 50 green, re-run after the test changes. The test is now no-parallel (Messes with internal cache), because the query cache is a server-global resource whose write policy declines rather than evicts when full, and capacity cannot be scoped by any tag, key or database; the runner confirms it lands in the sequential array. The cache-hit assertion was re-proven discriminating after that change: disabling cache reads on that statement flips exactly one output line from 1 to 0. An earlier run failed 15 of 50 on make_distributed_plan does not support parallel replicas, which is a collision between the distributed-plan assertion and the test runner's parallel-replicas randomization; parallel replicas are now pinned off on that one statement, and removing the pin fails 9 of 50 again.

Session id: cron:clickhouse-review-slot-48:20260730-230500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @davenger, could you review this? The approach changed since I first opened it: instead of refusing to decorrelate a subquery that uses WITH TOTALS, the decorrelation join now records which of its two inputs carries the subquery, and the physical join drops that input's totals and extremes before algorithm dispatch. So the subquery's totals no longer surface as the outer query's, while a legitimate totals stream on the other input still propagates.

groeneai and others added 2 commits July 31, 2026 01:34
The J rows of 04327_correlated_subquery_with_totals set make_distributed_plan = 1
to guard the distributed route for a correlated subquery. That optimizer refuses a
non-zero max_rows_to_group_by (makeDistributed.cpp, "A global GROUP BY limit can't
be enforced once aggregation is split per bucket"), and the value does not come from
the settings randomizer: tests/config/users.d/limits.yaml sets it to 10G and
tests/config/install.sh links that profile unconditionally, so every lane including
Fast test has it. The rows therefore failed deterministically with
SUPPORT_IS_DISABLED, and --no-random-settings could not help.

Pin the setting per statement rather than for the file, so the non-distributed
control rows keep running under the ambient profile, which is what makes them
controls. The EXPLAIN oracle row is pinned identically so it keeps describing the
same plan as the row it guards.

Verified against a server with the real limits profile installed: without the pin
the row fails with SUPPORT_IS_DISABLED, with it the result matches the
non-distributed oracle, and the Exchange oracle still reports a distributed plan, so
the pin does not make the optimizer silently decline. Removing either pin reddens the
test. Every other rejection in makeDistributed.cpp was checked against this shape:
the bucket-count cap, the pinned-block-number and virtual-column reads and GROUPING
SETS are unreachable here, and the read-in-order refusal was measured across
optimize_read_in_order, query_plan_read_in_order, read_in_order_use_virtual_row and
query_plan_read_in_order_through_join. 50 randomized runs pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
The decorrelation join is ANY OUTER. Partial merge supports only one of its two
orientations, so chooseJoinOrder clears flip_join whenever the algorithm list can
still select partial merge, and 'auto' is such a list. The stress runner injects
join_algorithm='auto', which left the forced-swap row planning the same join kind as
the row above it and silently not exercising the side reversal it exists to guard.

Measured from EXPLAIN, comparing each algorithm against its own no-swap baseline:
hash, parallel_hash, grace_hash and full_sorting_merge flip RIGHT to LEFT, while
'auto' and 'prefer_partial_merge' stay RIGHT. Under the runner's real pairing of
'auto' with max_rows_in_join the row plans RIGHT without the pin and LEFT with it, so
the pin restores the reversal.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4a2b233

Every failure below has an owner: a fixing PR (ours 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, sequential) / 04327_correlated_subquery_with_totals PR-caused: this PR's own new test. The last assertion, ProfileEvents['QueryCacheHits'] > 0, reads 0 instead of 1, and the runner reports it failed 3 out of 3 reruns, so it is deterministic on this job rather than flaky. Distinct from the known 1-in-200 rows: 3 race earlier in the same file: that one moves a JSONCompact row count, this one moves the trailing cache-hit row. CIDB has 2 hits in 30 days, both on this pull request, 0 on master fixed in this PR

Session id: cron:our-pr-ci-monitor:20260731-155315

The ParallelReplicas stateless jobs install tests/config/users.d/enable_parallel_replicas.xml,
which sets enable_parallel_replicas = 1 in the default profile. With it on, the subquery plan is
rewritten before the query cache entry is built, so the warm-up writes the entry under a key the
later reads never match: the read misses, a second distinct entry appears, and the final
ProfileEvents['QueryCacheHits'] > 0 row reads 0. That is the whole CI diff, a single flipped last
line, on amd_llvm_coverage/ParallelReplicas/s3/sequential.

Measured on the ambient profile: without the pin the hit row is 0 and with it 1, while the
JSONCompact block above is unchanged in both. Dropping the pin from the warm-up alone reproduces
the failure, so the writer and the readers have to agree on the key and all four cache statements
are pinned rather than only the write. With reads disabled the row still returns 0, so it keeps
measuring the cache rather than passing because the cache path was turned off.

The pin is per-statement, so the neighbouring rows that must run under ambient settings still do.
Master's imprecise-statistics EXPLAIN labelling (@ vdimir) rewrote the
join-order bookkeeping in optimizeJoin.cpp that this branch also touches:

  - setInputLabels/relation_names were replaced by
    setInputRelations/relation_infos, and
  - setOptimized dropped its lhs_estimation/rhs_estimation parameters in
    favour of an imprecise_estimate flag.

Resolved by taking master's side for both (the estimations it removed are
computed from entry->left/right, so nothing this branch needs is lost) and
keeping this branch's decorrelated-subquery-side re-derivation, which is
independent of either mechanism: it reads left_rels/right_rels, whose flip
semantics master did not change.
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 78/79 (98.73%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — eb6083d

CI is fully finished on this head (174 check-runs, 0 incomplete, Finish Workflow success). The one failure has an owner.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Equal values are not contiguous within the range assumed to be sorted (STID 2508-348f) intDiv(x, -1) is reported always-monotonic, so a stale sort property reaches DistinctSortedStreamTransform over an unsorted stream #112151 (ours, open)

Not caused by this PR. The aborting query is the fuzzer's mutation of the committed master test 04545_negative_limit_distinct.sql (intDiv(x, 100) mutated to intDiv(x, -1)):

SELECT DISTINCT intDiv(x, -1) AS d FROM nl ORDER BY d ASC NULLS FIRST OFFSET 9223372036854775806

Nothing in this PR touches DISTINCT-in-order, sort-property propagation, or arithmetic monotonicity. On master the variable / constant arm of FunctionBinaryArithmetic::getMonotonicityForRange ends in {true, is_constant_positive, true, is_strict}, so intDiv(signed, -1) is claimed always-monotonic even though it folds the signed minimum onto itself; #112151 intercepts that shape and reports non-monotonic for a range containing the wrap point. This build predates that fix, which is still open.

Session id: cron:our-pr-ci-monitor:20260801-180000

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

While re-checking a residual I had split out from an earlier review round of this PR, I measured
it and it does not warrant a change, so I am closing it rather than sending a follow-up.

The residual: in one 50/50 randomized local batch on 2026-07-31, the last JSONCompact block of
04327_correlated_subquery_with_totals returned "rows": 0 instead of "rows": 3 once, while the
following cache-hit assertion still printed 1. I had guessed the restoring INSERT was not yet
visible to the read after the preceding lightweight DELETE.

What the measurements say:

  • Not reproducible: 11 runs of that exact statement sequence on a pristine master debug build
    (5 uncached, 6 through the full cache section) returned "rows": 3 every time, and the
    delete-then-restore sequence reads 3 / 0 / 3 as intended. Total observed rate remains
    1 in 250 randomized local runs, against four earlier clean 50/50 batches and a clean 100-run batch.
  • Never seen in CI: over 180 days this test has 949 OK, 11 SKIPPED and 2 FAIL rows in the CI
    database. Both FAIL rows are different, already-fixed axes - the max_rows_to_group_by rejection
    fixed in 631a2644cd4a090, and the parallel-replicas cache-key mismatch fixed in
    6018b2f3ffe0fe7, whose own record reads Failed 3 out of 3 reruns with "rows": 3, i.e. it is
    deterministic and not this symptom. Both failing commits are ancestors of the current head, and
    there are 116 OK with 0 FAIL since the later fix. The four Stateless tests (*, flaky check)
    jobs on the current head all pass.
  • The hypothesis does not match what varies: none of lightweight_delete_mode, apply_patch_parts,
    lightweight_deletes_sync or any query_cache_* setting is randomized by tests/clickhouse-test,
    so pinning insert visibility would not pin the axis the runner actually moves.

If it reappears I will handle it as a round on this PR, which is where the test lives.

One conflict, in JoinStepLogical.h: master renamed the debug member
dummy_stats to table_stats_hint (Cascades cleanup, 8ba7569) in the
same region where this branch adds decorrelated_subquery_side. Took master's
rename and kept the new member; no dummy_stats reference remains in src/.

Master also added JoinStepLogical::swapInputs(), which swaps every
side-indexed member of the step (input headers, join kind, expression
sources, left/right relation). decorrelated_subquery_side names one of the
two inputs, so it has to be swapped there too, otherwise a swapped join
would drop totals and extremes from the wrong input. The Cascades
JoinCommutativity rule is the only caller and its pattern accepts an ANY
join, which is what decorrelation builds, so the marked join matches it.

Two conditions keep that from being reachable today, and neither is a
property of this join: Cascades needs make_distributed_plan = 1, and
optimizeTree.cpp refuses a plan carrying a TotalsHavingStep before Cascades
runs. Both are outside this member's control, so the swap is handled here
rather than relying on them.

Verified by compiling the five merged translation units against master's
new API: JoinStepLogical.cpp, JoinStep.cpp, optimizeJoin.cpp,
PlannerCorrelatedSubqueries.cpp, QueryPipelineBuilder.cpp, all rc=0. A
deliberate syntax error injected into the new swap block was rejected with
this worktree's own path and line number, which is what shows the compile
read these sources and not the snapshot's.

All 45 staged contrib gitlinks equal git rev-parse MERGE_HEAD:<path>, and
the diff against the merge parent is exactly the ten source and test files
of this PR with no contrib entry.
…he merge

Two corrections to the same comment, both about which code refuses which
route, not about the fix.

The cached-shape route named assertFragmentSerializable as the refuser.
That function has one call site, QueryPlan.cpp:932, reached only after
convertToDistributed passes canExecuteRemotely. A warm cache leaf is
ReadFromQueryResultCacheStep, which is not serializable, so
canExecuteRemotely returns false at makeDistributed.cpp:72 and the plan
falls back to local execution before line 932. Names the gate that runs.

The merge also brings plan-based parallel replicas, which gates a shipped
fragment on step serializability (subtreeIsShippable). That function did not
exist at this branch's merge base. Both this join and TotalsHavingStep
report serializable, so it does not reject them on that ground; with
correlated_subqueries_use_in_memory_buffer = 1, its default, the buffer
steps are not serializable and the fragment stays local. The
buffer-disabled shape is recorded as not established rather than argued,
and the list is marked open.
…o longer flattened

03836_tpch_join_order_plans asserts the join order of all 22 TPC-H queries. Q02 and Q17 are
the only two that contain a correlated subquery, so they are the only two this branch's join
guard reaches.

This branch records on the decorrelation join which of its two inputs carries the subquery,
and JoinStep::updatePipeline drops that input's totals and extremes. The recorded side only
identifies a physical input while the join still has exactly two of them, so optimizeJoin
refuses to flatten such a join into a wider graph and clamps its own graph to two relations.
Absorbing it would apply the drop to the wrong input, which is a silent wrong result.

The previous references had the decorrelation join absorbed under four (Q02) and one (Q17)
outer join ancestors, with the subquery's partsupp read reordered outside its own subtree in
Q02. It is now the top join over two subtrees in both. The plans are otherwise equivalent:
same table multiset, same number of joins, aggregations, filters and subquery-result markers;
only join order and exchange strategy differ.

The other 20 queries' expected plans are unchanged.
The comments at the five sites had accumulated the motivation, the root cause and the
serialization survey, and had grown to outnumber the code they annotate. Each is reduced to the
invariant a reader needs at that spot. No code change.

The rationale they carried, recorded here instead:

A subquery's totals and extremes are not part of the value it returns; the non-correlated scalar
evaluator consumes data chunks only. Decorrelation replaces the subquery with a join, and
joinPipelinesRightLeft propagates totals from whichever input has them, so they surfaced as the
outer query's totals. The carrier side is recorded in buildLogicalJoin, the only place where the
join's two inputs are unambiguous, and dropped in JoinStep::updatePipeline.

The side is not serialized, so a round trip drops it. That can only lose a drop, never move one
to the wrong input. Routes to a serialization boundary, as surveyed:

  - Boundary not reached. make_distributed_plan refuses a TotalsHavingStep-carrying plan
    (planHasUnsupportedDistributedStep). A warm query result cache escapes that scan, but serves
    from ReadFromQueryResultCacheStep, a non-serializable leaf, so canExecuteRemotely is false
    and the plan stays local. Under serialize_query_plan a correlated subquery cannot coexist
    with a remote table at all (validateCorrelatedSubqueries).
  - Boundary crossed, marker not needed. A set-subquery plan is serialized recursively, and
    addCreatingSetsTransform drops totals and extremes before building the set.
  - Not established. Plan-based parallel replicas gate a shipped fragment on step
    serializability (subtreeIsShippable). This join and TotalsHavingStep both report
    serializable, so that gate does not reject them; with
    correlated_subqueries_use_in_memory_buffer = 1 the buffer steps are non-serializable and do.
    The buffer-disabled shape is unmeasured.

A step carrying the subquery's totals across a boundary with neither property holding would need
the member serialized.
/// Set only on the decorrelation result join, and names which of its two inputs carries the
/// subquery. That input's totals and extremes are dropped rather than propagated
/// (`JoinStep::updatePipeline`), so the value is meaningful only while the join has two inputs.
/// Not serialized: an absent value drops no streams, it never names the wrong input.

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.

This Not serialized contract is not actually safe once correlated_subqueries_use_in_memory_buffer = 0. In the second pass we materialize CommonSubplanReferenceStep and remove CommonSubplanStep (optimizeTree.cpp:254-266), so the decorrelation join becomes fully serializable. applyParallelReplicas::liftSplitAboveJoin can then ship the whole LEFT/RIGHT ANY decorrelation join for plan-based parallel replicas, but JoinStepLogical::serialize still writes only the DAG/join operator and drops decorrelated_subquery_side. On the replica the physical JoinStep sees nullopt, stops stripping the subquery input's totals/extremes, and the original leak comes back for correlated WITH TOTALS / extremes = 1 queries under shipped fragments. Please either serialize this member or make marked decorrelation joins fail closed for remote execution.

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.

Agreed on the mechanism, and it is reachable more easily than stated. Two corrections and then my position.

coordinatedJoinSide (applyParallelReplicas.cpp:60-77) does not filter on strictness: it returns a side for Left or Right of any strictness, so JoinStrictness::Any is eligible. And at the default correlated_subqueries_default_join_kind = right, PlannerCorrelatedSubqueries.cpp:611 builds JoinKind::Right even with the buffer off, while the swap at :589 is gated on left && !buffer and does not fire. So correlated_subqueries_use_in_memory_buffer = 0 alone reaches this, together with parallel_replicas_plan_based = 1. The ordering also holds: the materialization at optimizeTree.cpp:254-266 runs before applyParallelReplicas at :393, and every remaining step in the subtree reports serializable (TotalsHavingStep.h:60, JoinStepLogical.h:108, AggregatingStep.h:118), so subtreeIsShippable does not reject the join.

Where I disagree is the severity. decorrelated_subquery_side has 0 occurrences at this branch's merge-base and 27 at its head, so it is new here, and its only effect is to drop totals and extremes from one input (JoinStep.cpp:146). It removes streams and changes no header. A replica that deserializes the join without it therefore behaves exactly as master behaves today, which is the #106920 leak itself. That is a corner this PR does not yet reach, not a regression it introduces, and reaching it needs an experimental setting that is off by default plus a non-default buffer setting. So I would not call it a blocker on this PR.

On your two remedies: failing closed is the better one. Returning false from isSerializable() while the marker is set makes liftSplitAboveJoin decline to lift, which leaves the split below the join exactly as the comment at :197 describes, so the coordinated read still distributes and only the join stays local. Serializing the member is a plan-format change and would need versioned upgrade and downgrade paths.

I am not making either change in this PR, because I cannot verify it here: this worktree cannot configure cmake (contrib/StringZilla/c/stringzilla/runtime.c is missing and contrib/MeCab is empty, and the fix for that is blocked by a submodule ownership check), and demonstrating the shape needs a multi-replica cluster. I will not ship an unverified change to a correctness path. Recording the boundary here instead: the fix covers local execution, and the plan-based parallel replicas path with the buffer disabled is not covered.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8b6d9dcf3 with master 889a93879 (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
Binary Master PR Δ
programs/clickhouse-stripped 702.07 MiB 699.05 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +149.0 s (+4%) in total before that adjustment.

Job report

@novikd novikd self-assigned this Aug 18, 2026
Comment on lines +148 to +149
if (decorrelated_subquery_side.has_value())
pipelines[*decorrelated_subquery_side == JoinTableSide::Left ? 0 : 1]->dropTotalsAndExtremesViaTransform();

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 Why so complicated? You do not need to pass decorrelated_subquery_side through all the JOIN logic.
Totals and Extremes could be dropped during the query decorrelation process.

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.

Fair question, and it was my first design. I built it, it broke working queries, and that is why the marker exists. Details, since they decide the shape of the alternative.

The first implementation added a DropTotalsAndExtremes plan step to the decorrelated subquery plan at exactly the point you are describing, and removed the NOT_IMPLEMENTED guard. It fixed the leak. It also made a query that returns a correct answer on master fail outright:

SET query_plan_optimize_join_order_algorithm = 'dpsize';  -- or 'dphyp'
-- master: 6.428571428571429
-- with the plan step: Code: 717 EXPERIMENTAL_FEATURE_ERROR
--   Failed to find a valid join order, try adding 'greedy' algorithm as fallback

joinOrder.cpp:682 solve <- optimizeJoinOrder <- optimizeJoin.cpp chooseJoinOrder. The default greedy was unaffected, which is why it is easy to miss. 34 stateless tests set dpsize or dphyp explicitly, and the setting is user-facing.

The cause is not placement. Plan optimizers locate their operands by single-hop exact-type typeid_cast on a join's direct child, e.g. convertAnyJoinToSemiOrAntiJoin.cpp:102:

if (auto * expression_before_join_step = typeid_cast<ExpressionStep *>(join_node->children[...]->step.get()))

12 files under Optimizations/ match a node's direct child by exact type this way. Any extra node between the decorrelation join and its subquery input hides the operand from all of them, so it is structural rather than one unlucky site. I also measured moving the node below the renaming step: the churn did not shrink and 03701 got worse. Regenerating the affected EXPLAIN references was not an option either, since they encoded a degraded plan (03734: 3 INNER joins became RIGHT, ALL became ANY).

So dropping at decorrelation time is right, but it has to happen without adding a node to the plan tree, because the tree shape is load-bearing for the optimizers. That is what the current change does: the drop decision is made in the decorrelation code (buildLogicalJoin, right after the default_join_kind swap so it follows the inputs), and it is consumed by the pipeline builder rather than by a plan node. Nothing is passed through the JOIN algorithms themselves. JoinStep::updatePipeline is where the pipeline is built at all, hence the drop being there.

If the objection is the plumbing through JoinStepLogical rather than the placement, there is a narrower variant I have not built: suppress the totals stream inside the subquery plan itself, by not creating the TotalsHavingStep's totals port for a correlated subquery, instead of dropping the stream after the fact. addTotalsHavingStep is reached at Planner.cpp:2547 under query_node.isGroupByWithTotals(), and the correlated subquery has its own Planner (buildPlannerForCorrelatedSubquery), so the knowledge is available there without touching join code at all. It removes the member, and it would also close the serialization gap the bot raised on this PR, since there would be nothing to serialize. What I do not know yet is whether TotalsMode::BEFORE_HAVING makes the totals stream observable through HAVING semantics, which would make suppression a result change rather than a no-op.

Tell me which you prefer and I will do that one. I would rather not push a variant on a wrong-result path without your call, having already had one design fail measurement.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@abashkeev abashkeev added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Dear @novikd, 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.

@novikd novikd self-assigned this Sep 25, 2026
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

The same leak now also causes a logical error on master. Since #118402, addTotalsHavingStep decorrelates a correlated subquery in HAVING before TotalsHavingStep, so when that subquery reads from a WITH TOTALS subquery, its totals come through the decorrelation join and TotalsHavingStep finds a totals stream already there:

SELECT number FROM numbers(10) GROUP BY number WITH TOTALS
HAVING EXISTS (SELECT 1 FROM (SELECT number AS n FROM numbers(5) GROUP BY number WITH TOTALS) WHERE n = number);
-- Logical error: 'Totals having transform was already added to pipeline'

Default settings, master 3e0adf02bef; master only, since #118402 is not in a release. The AST fuzzer found it through rewrite_in_to_join, which turns HAVING x IN (SELECT ... WITH TOTALS) into the same shape (report). It goes through the same result join of buildLogicalJoin that this PR handles, so I will add this case to 04327_correlated_subquery_with_totals when I update the PR.

@clickhouse-gh

clickhouse-gh Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Dear @novikd, 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.

@clickhouse-gh clickhouse-gh Bot added comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 19, 2026

This branch has not been deployed

No deployments
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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... 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.

Spurious TOTALS row in non-aggregate SELECT when WHERE contains a correlated scalar subquery using WITH TOTALS HAVING <expr over outer column>

6 participants