Skip to content

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

Description

@qoega

Spurious TOTALS block in the result of a non-aggregate SELECT when WHERE contains a correlated scalar subquery with GROUP BY ... WITH TOTALS

Summary

A top-level SELECT with no aggregation at all returns a totals block to
the client when its WHERE clause contains a correlated scalar subquery that
uses GROUP BY ... WITH TOTALS HAVING <expr over an outer column>.

The correlated-subquery decorrelation rewrites the scalar subquery into a
JOIN FillRightFirst whose left side contains a TotalsHaving step; the
totals block produced by that step propagates through the join into the
top-level pipeline and reaches the client as a totals row of the outer query.

The EXISTS decorrelation path already refuses this exact situation with
Code: 48. DB::Exception: Cannot decorrelate query, because 'TotalsHaving' step is not supported. (NOT_IMPLEMENTED) — the scalar-subquery path performs
the decorrelation anyway and produces the wrong output. Expected behaviour:
either reject like the EXISTS path, or decorrelate correctly without
leaking the subquery's totals into the outer result.

Found by the AST-fuzzer correctness oracle from PR
#99980 (TLP WHERE and
TLP DISTINCT oracles both trip on it: the partitioned query gains 2 extra
"rows" — the empty separator + totals row — versus the reference).

Minimal repro

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);
$ clickhouse local --queries-file repro.sql
0
1
2

0        <-- spurious totals block; the outer query has no aggregation

In FORMAT JSONCompact the result object likewise contains a "totals"
field. Reproduced on 26.6.1.1 (master 76c2edca2fd, release build) via
both clickhouse local and server.

Notes on the shape:

  • HAVING isNull(val) = 0 is load-bearing: it references the outer
    column val, making the subquery correlated. Without the HAVING, the
    uncorrelated scalar is evaluated separately and nothing leaks.
  • A bare outer-column reference (HAVING val >= 0) is rejected with
    NOT_AN_AGGREGATE, which looks inconsistent — isNull(val) is accepted
    where val is not — but that is a separate, minor concern.
  • The same shape inside EXISTS errors out instead of leaking:
    SELECT id FROM t WHERE exists((SELECT 1 FROM t AS u WHERE u.id = t.id GROUP BY 1 WITH TOTALS)) → NOT_IMPLEMENTED: Cannot decorrelate query, because 'TotalsHaving' step is not supported.

Plan (where the totals come from)

EXPLAIN PLAN SELECT id FROM t WHERE id >= (SELECT 0 GROUP BY 1 WITH TOTALS HAVING isNull(val) = 0);

Expression ((Project names + Projection))
  Filter
    Join (JOIN FillRightFirst)
      Expression (Left Pre Join Actions)
        Expression
          Join (JOIN FillRightFirst)
            Expression
              TotalsHaving            <-- subquery's totals step
                Aggregating
                  Expression ((Before GROUP BY + Change column names to column identifiers))
                    ReadFromSystemOne
            Filter
              ReadFromCommonBuffer
      Expression (Right Pre Join Actions)
        BuildRuntimeFilter (Build runtime join filter on __table1.val)
          SaveSubqueryResultToBuffer
            Expression (Change column names to column identifiers)
              ReadFromMergeTree (default.t)

Fix area

The correlated scalar-subquery decorrelation (planner, same place that emits
Cannot decorrelate query, because '...' step is not supported for the
EXISTS path — src/Planner/ correlated-subquery handling). Either add
TotalsHaving to the unsupported-step check for scalar subqueries as well,
or make the decorrelated join drop/contain the subquery's totals block so it
never reaches the outer query's output.

Original fuzzer hits (for reference)

  • 2026-06-09 11:52:53, cycle 7 instance 03 (TLP WHERE oracle), run dir
    tmp/fuzz_lab/runs/20260602-1228-0979ce58972/inst/03/:
    SELECT toString('...') FROM _s1 WHERE (d > (SELECT toLowCardinality(10) GROUP BY '\'', toInt256(-9223372036854775807), toNullable(-2147483649) WITH TOTALS HAVING isNull(g))) AND (toNullable(toLowCardinality(100)) <= d)
    — reference 500 rows, partitioned 502.
  • 2026-06-09 21:07:02, cycle 8 instance 01 (TLP DISTINCT oracle), run dir
    tmp/fuzz_lab/runs/20260609-1152-76c2edca2fd/inst/01/ (run_284.log):
    correlated EXISTS + GROUP BY ... WITH TOTALS inside or(...) —
    reference 500 rows, partitioned 502.

Activity

  1. qoega commented on Jun 10, 2026

    @qoega
    MemberAuthor

    @groeneai could you please reproduce and fix this one? Repro is in the issue body — deterministic on master 76c2edca2fd, default settings.

  2. added
    fuzz
    sqlancer
    on Jun 10, 2026
  3. groeneai commented on Jun 10, 2026

    @groeneai
    Collaborator

    @qoega reproduced and fixed in #107075.

    Root cause: correlated-subquery decorrelation rewrites the subquery into a JOIN, and JoinStep propagates totals from either input. When the correlated subquery's plan produces a totals stream (a TotalsHavingStep that isn't consumed by an enclosing AggregatingStep, which would drop it), that totals stream leaked through the decorrelation join into the outer non-aggregate pipeline and reached the client as a spurious totals row.

    The existing decorrelateQueryPlan "step not supported" throw only fires when the TotalsHaving step is itself correlated. In your repro HAVING isNull(val) = 0 puts the val correlation into a separate Filter step, leaving TotalsHaving in a non-correlated subplan that gets wrapped wholesale, so it was never rejected. On current master the EXISTS variant of your repro leaks the same way (it does not reject) — the rejection you observed happens only for the shape where the totals step itself is correlated.

    Fix: before decorrelating, walk the subquery plan and detect a TotalsHavingStep reachable from the result without crossing an AggregatingStep; if found, reject with NOT_IMPLEMENTED, for both the scalar and EXISTS paths (the option you suggested). A nested WITH TOTALS consumed by an enclosing aggregation, and WITH ROLLUP/WITH CUBE, are unaffected and keep working. Regression test 04327_correlated_subquery_with_totals added.

  4. added
    comp-query-analyzer
    on Sep 4, 2026
  5. clickgapai commented on Oct 8, 2026

    @clickgapai
    Contributor

    Same defect reproduced during automated review of PR #124096 (ClickGap), current master.

    Finding: rewrite_in_to_join totals fix skips views: leaked row and LOGICAL_ERROR

    Reproducer
    -- `WITH TOTALS` of a view read by the subquery on the right of `IN` must be ignored when `rewrite_in_to_join`
    -- rewrites the `IN` into a correlated `EXISTS`, as it is by the regular `IN` set.
    
    SET enable_analyzer = 1;
    SET allow_correlated_subqueries = 1;
    SET analyzer_inline_views = 0;
    
    DROP VIEW IF EXISTS v_totals;
    CREATE VIEW v_totals AS SELECT number FROM numbers(10) GROUP BY number WITH TOTALS;
    
    SELECT 'rewrite_in_to_join = 0';
    SET rewrite_in_to_join = 0;
    SELECT number FROM numbers(3) WHERE number IN (SELECT number FROM v_totals) ORDER BY number;
    SELECT number FROM numbers(3) WHERE number IN (SELECT number FROM view(SELECT number FROM numbers(10) GROUP BY number WITH TOTALS)) ORDER BY number;
    SELECT number FROM numbers(10) GROUP BY number WITH TOTALS HAVING number IN (SELECT number FROM v_totals WHERE number < 5) ORDER BY number;
    
    SELECT 'rewrite_in_to_join = 1';
    SET rewrite_in_to_join = 1;
    SELECT number FROM numbers(3) WHERE number IN (SELECT number FROM v_totals) ORDER BY number;
    SELECT number FROM numbers(3) WHERE number IN (SELECT number FROM view(SELECT number FROM numbers(10) GROUP BY number WITH TOTALS)) ORDER BY number;
    SELECT number FROM numbers(10) GROUP BY number WITH TOTALS HAVING number IN (SELECT number FROM v_totals WHERE number < 5) ORDER BY number;
    
    DROP VIEW v_totals;

    Expected:

    rewrite_in_to_join = 0
    0
    1
    2
    0
    1
    2
    0
    1
    2
    3
    4
    
    0
    rewrite_in_to_join = 1
    0
    1
    2
    0
    1
    2
    0
    1
    2
    3
    4
    
    0
    

    Actual:

    rewrite_in_to_join = 0
    0
    1
    2
    0
    1
    2
    0
    1
    2
    3
    4
    
    0
    rewrite_in_to_join = 1
    0
    1
    2
    
    0
    0
    1
    2
    
    0
    Received exception from server (version 26.10.1):
    Code: 49. DB::Exception: Received from 127.0.0.1:19020. DB::Exception: Totals having transform was already added to pipeline. (LOGICAL_ERROR)
    (query: SELECT number FROM numbers(10) GROUP BY number WITH TOTALS HAVING number IN (SELECT number FROM v_totals WHERE number < 5) ORDER BY number;)
    [ FAIL ] Reason: return code: 49 (identical on both runs)
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    comp-query-analyzerfuzzsqlancer

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions