Skip to content

Enforce invariant that ActionsDAG::Node::column is always ColumnConst - #100226

Merged
KochetovNicolai merged 25 commits into
masterfrom
column-set-always-const
May 22, 2026
Merged

KochetovNicolai merged 25 commits into
masterfrom
column-set-always-const

Conversation

@KochetovNicolai

@KochetovNicolai KochetovNicolai commented Mar 20, 2026 •

Copy link
Copy Markdown
Member
Opus 4.6 Always wrap `ColumnSet` in `ColumnConst` at all creation sites and add an assertion in `ActionsDAG::addNode` that rejects non-const columns (except for INPUT and PLACEHOLDER nodes). The `addInput(ColumnWithTypeAndName)` overload now strips non-const columns, keeping only propagated constants.

Since ColumnSet is now always inside ColumnConst, FunctionIn disables useDefaultImplementationForConstants to avoid the framework changing input_rows_count from 0 to 1 during header computation with unready sets. Instead, it handles constant unwrapping for the left argument manually and returns ColumnConst results for empty sets and const inputs explicitly.

FilterTransform no longer calls expression->execute() in its constructor (which would fail with unready sets). It uses ActionsDAG::updateHeader (dry-run evaluation) for the initial header, then re-evaluates the filter via expression->execute in prepare() once sets are ready (output.isNeeded()), enabling constant-fold early exit for expressions like WHERE x IN (empty set).

The old analyzer's ExpressionAnalysisResult had the same issue — it called ExpressionActions::execute on sample blocks for early constant folding of WHERE/PREWHERE before sets were built. Replaced with ActionsDAG::updateHeader which uses dry-run evaluation.

Propagate dry_run through lambda execution: ColumnFunction::reduce, ExecutableFunctionExpression, and FunctionArrayMapped now forward the flag so that FunctionIn inside lambdas (e.g. arrayExists(x -> x IN ...)) correctly returns placeholder results during dry-run evaluation.

Remove ExpressionActions::checkColumnIsAlwaysFalse — superseded by the general constant-fold check in FilterTransform::prepare.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.92

@clickhouse-gh

clickhouse-gh Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [de872f1]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Integration tests (arm_binary, distributed plan, 3/4) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
test_storage_iceberg_with_trino/test.py::test_clickhouse_writes_trino_reads FAIL cidb, issue ISSUE EXISTS
Integration tests (amd_tsan, 2/6) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Integration tests (amd_msan, 2/6) FAIL
test_mysql_protocol/test.py::test_mysql_dotnet_client FAIL cidb IGNORED
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL IGNORED

AI Review

Summary

This PR enforces the ActionsDAG::Node::column const-invariant around ColumnSet and reworks dry-run behavior for IN plus filter-header evaluation. The direction is correct, but current head still has one correctness regression in FunctionIn for zero-row runtime chunks with delayed sets (already discussed and dismissed) and one new prepare lifecycle issue that can skip the intended empty-set early-stop optimization.

Findings

❌ Blockers

  • [src/Functions/in.cpp:109-124] future_set->get() is still evaluated before the non-dry_run input_rows_count == 0 fast path, so a zero-row runtime chunk can still throw Not-ready Set is passed ... instead of behaving as a no-op. [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/100226#discussion_r3233774669] The path is still reachable because ISimpleTransform::work calls transform on empty chunks (src/Processors/ISimpleTransform.cpp:100) and FilterTransform::doTransform forwards that row count to expression->execute (src/Processors/Transforms/FilterTransform.cpp:179). Suggested fix: restore the zero-row short-circuit for non-dry_run before set-readiness checks, while keeping current dry_run handling for header evaluation.

⚠️ Majors

  • [src/Processors/Transforms/FilterTransform.cpp:122-135] are_prepared_sets_initialized is set to true on the first output.isNeeded() call even though sets may still be unready at that point (as the comment itself notes). If the first dry-run reevaluation happens too early, always_false stays false and is never recomputed after set readiness changes, so WHERE ... IN (empty set) can miss the intended early-stop path. Suggested fix: keep reevaluating until sets are actually initialized (for example, keep the previous status != PortFull-style gating, or equivalent explicit readiness gating).
Tests
  • ⚠️ Add a focused regression test for zero-row runtime execution with delayed RHS set build in filter evaluation, proving no exception is thrown and behavior stays no-op.
  • ⚠️ Add a regression test where set readiness changes after initial prepare so FilterTransform still detects constant-false filters (IN (empty set)) and stops early.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
  1. Fix FunctionIn zero-row non-dry_run readiness ordering.
  2. Fix FilterTransform::prepare recheck lifecycle so empty-set early-stop is not one-shot before set readiness.
  3. Add targeted regression tests for both behaviors.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Mar 20, 2026
KochetovNicolai and others added 3 commits March 27, 2026 16:35
…nst`

Always wrap `ColumnSet` in `ColumnConst` at all creation sites and add an
assertion in `ActionsDAG::addNode` that rejects non-const columns (except
for INPUT and PLACEHOLDER nodes). The `addInput(ColumnWithTypeAndName)`
overload now strips non-const columns, keeping only propagated constants.

Since `ColumnSet` is now always inside `ColumnConst`, `FunctionIn` disables
`useDefaultImplementationForConstants` to avoid the framework changing
`input_rows_count` from 0 to 1 during header computation with unready sets.
Instead, it handles constant unwrapping for the left argument manually and
returns `ColumnConst` results for empty sets and const inputs explicitly.

`FilterTransform` no longer calls `expression->execute()` in its constructor
(which would fail with unready sets). It uses `ActionsDAG::updateHeader`
(dry-run evaluation) for the initial header, then re-evaluates the filter
via `expression->execute` in `prepare()` once sets are ready
(`output.isNeeded()`), enabling constant-fold early exit for expressions
like `WHERE x IN (empty set)`.

The old analyzer's `ExpressionAnalysisResult` had the same issue — it called
`ExpressionActions::execute` on sample blocks for early constant folding of
WHERE/PREWHERE before sets were built. Replaced with
`ActionsDAG::updateHeader` which uses dry-run evaluation.

Propagate `dry_run` through lambda execution: `ColumnFunction::reduce`,
`ExecutableFunctionExpression`, and `FunctionArrayMapped` now forward the
flag so that `FunctionIn` inside lambdas (e.g. `arrayExists(x -> x IN ...)`)
correctly returns placeholder results during dry-run evaluation.

Remove `ExpressionActions::checkColumnIsAlwaysFalse` — superseded by the
general constant-fold check in `FilterTransform::prepare`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…gTransform`

`FilterTransform::prepare` used `expression->execute(header)` to re-evaluate
the filter once output is needed. This fails for mutations where
`DelayedPorts` delays data flow but not the `isNeeded` signal, so sets may
not be ready yet. Use `ActionsDAG::updateHeader` (dry-run) instead.

`TotalsHavingTransform` constructor had the same issue — add a comment
documenting the existing `updateHeader` usage.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@KochetovNicolai
KochetovNicolai force-pushed the column-set-always-const branch from c8619f8 to 385365d Compare March 27, 2026 18:35
Comment thread src/Columns/ColumnFunction.cpp Resolved
KochetovNicolai and others added 10 commits March 30, 2026 13:53
…for `ColumnSet`

Since `ColumnSet` is now always wrapped in `ColumnConst`, the bare
`checkAndGetColumn<ColumnSet>` check no longer finds it. Add
`checkAndGetColumnConstData` as the primary check so that sets from
subqueries are properly found and built before the DAG is executed.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The test checks that sets are not built when `use_skip_indexes = 0`.
However, when `auto_statistics_types` is set (via random MergeTree
settings fuzzing), the statistics machinery builds the set as a side
effect, causing `throwIf(1)` to fire unexpectedly.

Disable `use_statistics` in the EXPLAIN queries to prevent this.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Same root cause as `02707_skip_index_with_in`: when `auto_statistics_types`
is set via random MergeTree settings fuzzing, the statistics machinery
changes the query plan (removing `CreatingSet` nodes). Disable
`use_statistics` to keep the plan stable.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
When `auto_statistics_types` is set via random MergeTree settings fuzzing,
the statistics machinery reads extra rows, exceeding the `max_rows_to_read`
limit the test relies on. Disable `use_statistics` in both the base test
and the `_with_null` variant.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The nested `arg->reduce()` calls in the short-circuit argument handling
were not forwarding the `dry_run` flag, dropping the dry-run context
for nested lambda arguments.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Comment thread src/Functions/in.cpp
if (set->getTotalRowCount() == 0)
return ColumnConst::create(ColumnUInt8::create(1, negative), input_rows_count);

if (input_rows_count == 0)

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.

executeImpl now checks future_set->get() before the input_rows_count == 0 fast path. In non-dry_run execution this means an empty block can now throw Not-ready Set is passed ... if set creation is delayed, even though with zero rows we should be able to return an empty result without touching set readiness.

Could we keep the zero-row short-circuit for non-dry_run (as before), and keep the new empty-set constant handling specifically for dry_run header evaluation?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this will hide the potential error behavior. To evaluate a header, we execute with dry_run. In other cases, I think it's better to throw an error even if input_rows_count == 0.

I will keep the code as is if the tests pass.

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.

I still think this is a real behavior regression.

FilterTransform::doTransform executes the expression with num_rows_before_filtration (runtime path, not dry_run). If a zero-row chunk is processed before the set is ready, FunctionIn::executeImpl now throws at future_set->get() / Not-ready Set is passed... before it reaches the input_rows_count == 0 branch.

For zero input rows we should be able to return an empty result without touching set readiness. Throwing here turns an empty-block no-op into a query exception.

Can we restore the zero-row fast path for non-dry_run execution (while keeping the new dry-run behavior for header evaluation)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still don't think it's a regression.

FilterTransform::doTransform should not be run when there is not-ready set. It does not matter if input_rows_count is zero or not.

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.

I re-checked this against the current code and the concern is still live.

ISimpleTransform::work still invokes transform even when chunk.getNumRows() == 0 (src/Processors/ISimpleTransform.cpp:100), and FilterTransform::doTransform forwards that num_rows_before_filtration to expression->execute (src/Processors/Transforms/FilterTransform.cpp:179). In FunctionIn::executeImpl, the non-dry_run path now calls future_set->get() and throws for not-ready sets before reaching if (input_rows_count == 0) (src/Functions/in.cpp:109-124).

So an empty runtime chunk can now fail with Not-ready Set is passed ... where it previously returned an empty result. This is a behavior regression: zero-row execution should be a no-op with respect to set readiness.

Could we restore the zero-row fast path for non-dry_run execution (while keeping the dry-run header behavior)?

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.

I re-checked this on the current head and the regression is still present.

FunctionIn::executeImpl still calls future_set->get() (and throws on not-ready sets) before the input_rows_count == 0 branch (src/Functions/in.cpp, lines 109-124). Runtime execution can still hit this path with empty chunks: ISimpleTransform::work always calls transform even for zero-row chunks (src/Processors/ISimpleTransform.cpp:100), and FilterTransform::doTransform forwards num_rows_before_filtration to expression->execute (src/Processors/Transforms/FilterTransform.cpp:179).

So a zero-row runtime chunk can still fail with Not-ready Set is passed ... instead of behaving as a no-op. Could we restore the zero-row fast path for non-dry_run execution (while keeping the dry-run/header behavior)?

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.

I re-checked the current head and the concern is still live.

In FunctionIn::executeImpl, the non-dry_run path still calls future_set->get() (and can throw Not-ready Set is passed ...) before the input_rows_count == 0 branch. Runtime can still pass empty chunks through this path: ISimpleTransform::work invokes transform even for zero-row chunks, and FilterTransform::doTransform forwards that row count to expression->execute.

So an empty runtime chunk can still raise an exception instead of behaving as a no-op. Please restore the zero-row short-circuit before set-readiness checks for non-dry_run execution (while keeping the current dry-run/header behavior).

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.

Re-checked on the latest head (da5be0d) and this regression is still present.

FunctionIn::executeImpl still resolves future_set->get() before if (input_rows_count == 0), so a not-ready RHS set still throws Not-ready Set is passed ... even for an empty input chunk. Runtime can still reach this path with zero rows: ISimpleTransform::work always calls transform (src/Processors/ISimpleTransform.cpp:100), and FilterTransform::doTransform passes that row count into expression->execute (src/Processors/Transforms/FilterTransform.cpp:179).

Please restore the zero-row fast path for non-dry_run execution before set-readiness checks (while keeping the current dry-run/header behavior).

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.

Re-checked on current head (da5be0d): this is still a behavior regression.

In FunctionIn::executeImpl, future_set->get() is still evaluated before if (input_rows_count == 0), so a not-ready RHS set can still throw Not-ready Set is passed ... even for an empty runtime chunk.

Runtime can reach this path with zero rows: ISimpleTransform::work still calls transform on empty chunks, and FilterTransform::doTransform forwards that row count to expression->execute.

Please restore the zero-row fast path for non-dry_run execution before set-readiness checks (keeping current dry_run handling for header evaluation).

@devcrafter

Copy link
Copy Markdown
Member

Related to #90363

Comment thread src/Interpreters/ActionsDAG.cpp Outdated
Comment on lines 285 to 291
if (res.type != ActionType::PLACEHOLDER)
{
const auto valid_column = !res.column || (res.column->isConst() || typeid_cast<const ColumnSet *>(res.column.get()) != nullptr);
if (!valid_column)
res.column = nullptr;
if (res.column && !isColumnConst(*res.column))
throw Exception(ErrorCodes::LOGICAL_ERROR,
"ActionsDAG node column must be a ColumnConst, got {} for '{}'",
res.column->getName(), res.result_name);
}

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.

Maybe let's do this check before we emplace the node inside nodes?

Also, the AI description states: that rejects non-const columns (except for INPUT and PLACEHOLDER nodes).. It would still reject an INPUT node.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Never trust AI :)

Comment thread src/Planner/PlannerActionsVisitor.cpp Outdated
Comment on lines +1019 to +1020
auto column_set = ColumnSet::create(1, std::move(set));

if (set_is_created)
column.column = ColumnConst::create(std::move(column_set), 1);
else
column.column = std::move(column_set);
column.column = ColumnConst::create(std::move(column_set), 1);

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.

Suggested change
auto column_set = ColumnSet::create(1, std::move(set));
if (set_is_created)
column.column = ColumnConst::create(std::move(column_set), 1);
else
column.column = std::move(column_set);
column.column = ColumnConst::create(std::move(column_set), 1);
column.column = ColumnConst::create(ColumnSet::create(1, std::move(set));, 1);

{
auto header = expression->getActionsDAG().updateHeader(getInputPort().getHeader());
auto & column = header.getByPosition(filter_column_position).column;
if (column)

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.

When it is possible to not have a column? Maybe let's throw a LOGICAL_ERROR.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, usually we create columns in the header. But I don't want to fix it now, cause we don't strictly check this invariant

/// where the result becomes known only after the set is built.
/// Use updateHeader (dry-run) because sets may not be ready yet even when
/// output.isNeeded() is true (e.g. delayed set creation in mutations).
if (!are_prepared_sets_initialized && output.isNeeded())

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.

Maybe we can also skip the re-evaluation when always_false is already set. I am not sure if it worth the clutter or not, but thought will mention it.

Comment on lines +1066 to +1067
if (!column_set)
column_set = checkAndGetColumn<ColumnSet>(node.column.get());

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.

If we wrap the set in const column, how is it possible to not have it as const column? Especially because below we don't do this. Maybe it worth a comment if this really the case.

Suggested change
if (!column_set)
column_set = checkAndGetColumn<ColumnSet>(node.column.get());

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to fix it in a follow-up PR

KochetovNicolai and others added 7 commits May 20, 2026 13:56
`FunctionCapture` (the IFunctionBase backing a lambda) inherited the
default `isSuitableForConstantFolding() == true`, so the analyzer would
happily fold `arrayMap(x -> f(x), [...const array...])` even when `f`
was non-deterministic or referenced an IN set whose RHS hadn't been
built yet. The folded value (computed with `dry_run=true`) would be
cached on the DAG node and reused at execution time, producing wrong
results — most visibly for non-deterministic WASM UDFs whose dry-run
returns defaults (test `04212_bare_function_name_as_lambda_wasm`).

Walk the lambda's inner DAG and propagate the existing constant-folding
suitability up:

- A FUNCTION node disqualifies the lambda if its `function_base`
  reports `isSuitableForConstantFolding() == false`.
- A COLUMN node disqualifies the lambda if it wraps a `ColumnSet`
  whose `FutureSet` isn't ready — same check `getFunctionArguments`
  already performs for direct children of a function node.
- ARRAY_JOIN and PLACEHOLDER nodes inside a lambda also disqualify it.

This lets `addFunctionImpl`'s `all_const` check fall through cleanly:
with the lambda's `node.column` left null, the outer higher-order
function isn't const-folded either, and the inner functions run for
real at execution time.

While here: also stop forwarding the outer `dry_run` flag into the
lambda body in `ExecutableFunctionExpression::executeImpl`. With the
suitability check above, this can't reach a non-deterministic call
through constant folding anymore, but reverting the propagation keeps
the lambda boundary opaque (matches pre-PR behaviour) and avoids
similar surprises if anyone else ever dry-runs through a lambda.

Adjust `evaluateConstantExpression` to apply `cloneResized(1)` after
both the new- and old-analyzer branches: DAG nodes now hold size-zero
ColumnConsts (per the `addColumn` invariant), so the existing
`empty()` check would otherwise reject a perfectly valid constant.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
(cherry picked from commit e63378a)
/// output.isNeeded() is true (e.g. delayed set creation in mutations).
if (!are_prepared_sets_initialized && output.isNeeded())
{
are_prepared_sets_initialized = true;

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.

are_prepared_sets_initialized is set to true before we know that sets are actually ready.

In this same block we note that sets may still be unready even when output.isNeeded() == true. If that happens, this one-shot updateHeader run sees a placeholder/non-constant result and we never re-check after the set becomes ready, so always_false stays false and we miss the intended early-stop optimization for WHERE ... IN (empty set).

Can we keep re-evaluating until sets are definitely initialized (for example, set this flag only after the pipeline leaves the pre-init phase, as in the previous status != PortFull logic)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the comment mentions a corner case, and this should not normally happen. Sets should already be build when the port is needed. Otherwise, we get not-ready set in work(). Re-evaluation might be expensive

@clickhouse-gh

clickhouse-gh Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 93.49% (201/215) | lost baseline coverage: 5 line(s) · Uncovered code

Full report · Diff report

@KochetovNicolai
KochetovNicolai added this pull request to the merge queue May 22, 2026
Merged via the queue into master with commit 46bbacc May 22, 2026
320 of 328 checks passed
@KochetovNicolai
KochetovNicolai deleted the column-set-always-const branch May 22, 2026 13:17
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 22, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 25, 2026
Per @Algunenano review on PR ClickHouse#105675: dry_run has only 3 real use cases in
the codebase, and the original ClickHouse#105650 fuzzer finding is already masked on
master by ClickHouse#100226 (ColumnConst node invariant + dry_run propagation in
lambda execution). Adding more dry_run plumbing without a current
behavioural bug to back it is unjustified.

Keep the regression test (04274_105650_isNotDistinctFrom_string_group_by)
so the fuzzer query and a minimised isNotDistinctFrom + WITH ROLLUP form
remain exercised on master HEAD.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…s-const

Enforce invariant that `ActionsDAG::Node::column` is always ColumnConst
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 23, 2026
…d analyzer

The old analyzer replaces `in` with `inIgnoreSet` while it only needs the
types, passing the left operand as the stand-in for the set that is not built
yet. The general typing rule wraps the result in `LowCardinality` only when
every other argument is a constant, so two full `LowCardinality` arguments
typed the expression as plain `UInt8`, while executing the real `in` against
the constant `Set` column yields `LowCardinality(UInt8)`.

A query reading such a column across a subquery boundary then recorded
`UInt8` in the outer `ActionsDAG` and got `LowCardinality(UInt8)` in the
header, failing the type check in `ActionsDAG::updateHeader`:

    SET enable_analyzer = 0;
    SELECT tuple(*) FROM (SELECT s, s IN (SELECT 'a') AS f FROM t);
    -- Unexpected return type from tuple. Expected Tuple(LowCardinality(String), UInt8).
    --          Got Tuple(LowCardinality(String), LowCardinality(UInt8)). (LOGICAL_ERROR)

Pass a constant `UInt8` as the stand-in instead. It is indistinguishable from
the real `Set` argument in every dimension the typing rule inspects, so
analysis and execution agree by construction for all eight `in` variants and
every operand shape. A `Set`-typed stand-in would mirror execution more
literally, but the window-definition expressions built by
`getRootActionsNoMakeSet` end up in an executed plan, and a `ColumnSet` with
no set behind it would be dereferenced when such a plan is serialized.

`allow_experimental_analyzer = 1` was fixed for the same root cause in
ClickHouse#114229, whose test is tagged
`no-old-analyzer`; the divergence appeared when `ColumnSet` became always
constant in ClickHouse#100226.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 26, 2026
The fold added in this PR refuses a storage-backed set, because an `INSERT` grows
it in place after planning. `executeImpl` still returned a `ColumnConst` for any
empty set, so header evaluation produced a constant where the DAG node stayed a
function, which is the mismatch this PR is about. An empty `ENGINE = Set` table
under `ARRAY JOIN` therefore still threw:

    CREATE TABLE s (x Int) ENGINE = Set;
    SELECT count() FROM t ARRAY JOIN [b] AS x WHERE a IN s;  -- Code: 44

Measured: correct on 26.3.23.2, `Code: 44` on 26.7.6.15, on pristine master and on
the previous head of this PR. So it is the same regression as the tuple-set carrier
rather than an older bug, and the description's claim that only the tuple-set
carrier throws on master was wrong.

Both paths now use `isImmutableEmptySet`, so a set kind is constant in the DAG and
in the header or in neither. An empty subquery set already answered correctly for
the mirror-image reason: `FutureSetFromSubquery::get` returns null during analysis,
so header evaluation never saw a constant there.

The always-false exit of ClickHouse#100226 is unaffected: a literal `IN ()` is a tuple set
and still folds to `Filter column: 0`. For the excluded kinds the empty set now
goes through `Set::execute`, which returns an all-`negative` column.

Every stateless test using `ENGINE = Set` (25 files) plus the empty-subquery-set
and plan-shape tests ran on the previous head and on this commit: 28 of 29
byte-identical, the only difference being the new arms of this PR's test. The new
empty-storage arm throws `Code: 44` on the previous head.
leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Sep 2, 2026
An ARRAY JOIN with a WHERE filter on a different column against an empty
IN set was rejected with

  Code: 44. Cannot convert column `in(...)` because it is non constant in
  source stream but must be constant in result. (ILLEGAL_COLUMN)

as in

  CREATE TABLE t (a Int, b Int) ENGINE = MergeTree ORDER BY tuple();
  INSERT INTO t VALUES (1, 2);
  SELECT count() FROM t ARRAY JOIN [b] AS x WHERE a IN ();

FunctionIn disables the default constant-folding wrapper and folds by
hand, but it never declared the fold it actually performs: for a set that
is built and empty, executeImpl returns a ColumnConst whatever the left
operand is. The DAG answers a different question. With a non-constant
left operand getFunctionArguments reports all_const = false, so
tryFoldFunctionToConstant calls getConstantResultForNonConstArguments,
which FunctionIn did not override, so the node stayed non-constant. Yet
ActionsDAG::updateHeader separately executes the function at
input_rows_count = 0 and does reach the empty-set branch, so the header
column is a ColumnConst. ARRAY JOIN rebuilds the block from the
non-constant node, which is what forces the two headers to be compared,
so blocksHaveEqualStructure fails and makeConvertingActions throws.

The asymmetry became reachable in ClickHouse#100226, which moved the empty-set
check ahead of the input_rows_count == 0 early return; before that the
branch returned a non-constant column and both sides agreed. Reverting
that ordering was rejected because it would re-break the
ConstantFilterDescription always-false exit in FilterTransform::prepare()
that ClickHouse#100226 was written for. Adding the override keeps both properties.

The fold applies only when the set is already built (a not-yet-built
subquery set may still turn out non-empty) and empty, and when the result
type carries no Nullable: NULL IN () is NULL rather than 0, so folding
those to UInt8 would produce wrong results. LowCardinality(String)
operands and the notIn and nullIn variants were failing the same way and
are covered by the same override.

Measured against pristine master, 10 of 32 probed query shapes move from
Code: 44 to the correct value and the other 22 are byte-identical. The
new test's expected values were cross-checked against unpatched master's
own working shape (with prewhere optimizations disabled) so they encode
pre-regression semantics. Removing only the Nullable guard makes
NULL IN () return 0, which the test catches. Re-running the failures of
the whole _in test pattern against pristine master under an identical
workload showed no regressions across the 248 tests run on both arms.

Closes: ClickHouse#116018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants