Repository navigation
Conversation
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]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-2:20260610-193654 |
|
cc @novikd @vdimir — could you review this? It fixes #106920: a correlated scalar/EXISTS subquery using |
|
Workflow [PR], commit [8b6d9dc] Summary: ❌
AI ReviewSummaryThis PR fixes leaked subquery Findings❌ Blockers Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 84/85 (98.82%) · Uncovered code |
|
CI finished on
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 |
|
@groeneai update branch and make CI green |
|
Done. Merged current master into the branch; HEAD is now The merge is clean (no conflicts) and 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. |
|
CI re-ran on the updated branch (HEAD
Session: cron:our-pr-ci-monitor:20260617-193000 |
…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.
TOTALS into the outer query
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 My own cold review found no blockers and no majors. I enumerated the invariant carriers ❌ Agreed, fixed in this round
💡 Noted, not blocking Two items the implementation reported instead of working around: a prescribed liveness proof for one Session id: cron:clickhouse-review-slot-48:20260730-230500 |
Pre-PR validation gate
Randomized runs: 50 of 50 green, re-run after the test changes. The test is now Session id: cron:clickhouse-review-slot-48:20260730-230500 |
|
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. |
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]>
CI finish ledger - 4a2b233Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 78/79 (98.73%) · Uncovered code |
CI finish ledger — eb6083dCI is fully finished on this head (174 check-runs, 0 incomplete,
Not caused by this PR. The aborting query is the fuzzer's mutation of the committed master test SELECT DISTINCT intDiv(x, -1) AS d FROM nl ORDER BY d ASC NULLS FIRST OFFSET 9223372036854775806Nothing in this PR touches DISTINCT-in-order, sort-property propagation, or arithmetic monotonicity. On master the Session id: cron:our-pr-ci-monitor:20260801-180000 |
|
While re-checking a residual I had split out from an earlier review round of this PR, I measured The residual: in one 50/50 randomized local batch on 2026-07-31, the last What the measurements say:
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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units402 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. |
| if (decorrelated_subquery_side.has_value()) | ||
| pipelines[*decorrelated_subquery_side == JoinTableSide::Left ? 0 : 1]->dropTotalsAndExtremesViaTransform(); |
There was a problem hiding this comment.
@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.
There was a problem hiding this comment.
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.
|
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. |
|
The same leak now also causes a logical error on master. Since #118402, 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 |
|
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. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a spurious
TOTALSblock returned for a non-aggregateSELECTwhoseWHEREcontains a correlated subquery usingGROUP BY ... WITH TOTALS. The subquery's totals are no longer propagated as the outer query's totals.Description
Closes: #106920
A non-aggregate
SELECTreturned an extra totals row when itsWHEREcontained a correlated scalar orEXISTSsubquery producing a totals stream: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, andjoinPipelinesRightLeftpropagates totals from whichever input has them.The change.
buildLogicalJoinis the only place where the join's two inputs are unambiguous, so it records there which input carries the subquery (after thecorrelated_subqueries_default_join_kindswap, so one expression covers both values).JoinStep::updatePipelinedrops that input's totals and extremes at the top, before theswap_streamsswap 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 by03808_correlated_subquery_with_totals).That side is only meaningful while the join has two inputs, so the existing swap-only
query_graph_size_limit = 2clamp 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 andEXISTS, nested totals, both values ofcorrelated_subqueries_default_join_kindandcorrelated_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.referencethis PR changes is the new one.Workflow [PR]
Sync PR [sync-upstream/pr/107075]