Skip to content

Fix ILLEGAL_COLUMN for an empty IN set with ARRAY JOIN - #116057

Merged
fm4v merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-in-empty-set-array-join
Sep 2, 2026
Merged

fm4v merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-in-empty-set-array-join

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Fix ILLEGAL_COLUMN for an empty IN set with ARRAY JOIN

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed ILLEGAL_COLUMN ("Cannot convert column ... because it is non constant in source stream but must be constant in result") for a query combining ARRAY JOIN with a filter on an empty IN set, whether the set is an empty list such as SELECT count() FROM t ARRAY JOIN [b] AS x WHERE a IN () or an empty ENGINE = Set table. Closes #116018.

Description

Closes: #116018
Related: #100226

Under ARRAY JOIN, a WHERE filter on another column against an empty IN set was rejected.

SELECT count() FROM t ARRAY JOIN [b] AS x WHERE a IN ();  -- Code: 44, expected 0

Root cause. For a built, empty set executeImpl returns a ColumnConst whatever the left operand is, but the DAG node did not say so: FunctionIn never overrode getConstantResultForNonConstArguments, so the node stayed non-constant while ActionsDAG::updateHeader executed the function and got a ColumnConst. ARRAY JOIN makes the two headers meet, and makeConvertingActions throws. #100226 made this reachable by moving the empty-set check ahead of the input_rows_count == 0 return.

The change adds that override, so the node reports the constant executeImpl already returns. Only an empty FutureSetFromTuple folds in the node: it is finished in its constructor and never mutated, while a subquery set has to stay in the plan for shard-side index analysis. In executeImpl an empty set is constant for every kind but a storage-backed one, which is readable before the pipeline exists and would otherwise leave a constant in a declared header the stream cannot fill. IN () still folds to Filter column: 0, so the always-false filter exit #100226 was written for is intact. LowCardinality(String), notIn and nullIn are fixed too.

Validation. Both carriers, an empty tuple set and an empty ENGINE = Set table under ARRAY JOIN, are correct on 26.3.23.2 and give Code: 44 on 26.7.6.15, so both are the same regression. Each guard is pinned in both directions by tests already in the tree: 03302_analyzer_distributed_filter_push_down for the subquery kind, 01015_empty_in_inner_right_join and 04545_correlated_subquery_in_set_speculative_build for the storage-backed one, and the NULL IN () arms for the Nullable guard. A 59-test sweep over the ENGINE = Set and empty-IN families shows no other verdict change.


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

Version info

  • Backported to: 26.8.3.14, 26.7.7.9, 26.6.5.101

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
Review round 1 on the empty-IN-set fold.

The fold's readiness test was future_set->get(), which is the right question for
a subquery set (FutureSetFromSubquery::get returns null unless the set is
created) but no test at all for a storage-backed one: FutureSetFromStorage::get
returns its SetPtr unconditionally, and StorageSet::insertBlock inserts into
that same Set object in place. A folded node becomes an ActionType::COLUMN, and
ExpressionActions then skips executing the function entirely, so a query planned
while an ENGINE = Set table was empty would keep answering with the folded
constant after rows arrived. Fold only against a set whose contents can no
longer change: a tuple set, or a subquery set that is already created.

The regression test also pins both prewhere settings. The bug is armed only when
prewhere runs, and the two settings are independently randomized to False at
p=0.05 each, so both were on in only 90% of runs, measured over 4000 draws of
the randomizer. Without the pin the test silently stops reproducing on roughly
one run in ten. It is pinned per setting rather than with no-random-settings so
the remaining randomization still covers the test.

Arming is asserted by node shape rather than by a result value, because the
empty-then-INSERT sequence returns the same values whether or not the fold
happens: with a literal empty list the filter becomes a constant, while with an
empty ENGINE = Set table the in() function survives in the plan. Removing just
the new set-kind guard flips both of those assertions.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two review rounds. Round 1 found a wrong-results blocker and a vacuous-oracle major, both fixed
in 73091854021089a. Round 2: independent cold review 0 blockers / 0 majors, second-model gate
0 findings.

❌ Blocker (round 1, fixed) - the fold's readiness guard future_set->get() is a real
predicate for a subquery set (FutureSetFromSubquery::get() returns null unless isCreated())
but none at all for a storage-backed one: FutureSetFromStorage::get() returns its set
unconditionally, and StorageSet::insertBlock grows that same Set in place. A folded node
becomes ActionType::COLUMN, which ExpressionActions never executes, so a query planned while
an ENGINE = Set table was empty would keep answering the folded constant after rows arrived.
Fixed by folding only for immutable set kinds (tuple, created subquery) and returning nullptr
for anything else, so a future FutureSet subclass defaults to not folding.

⚠️ Major (round 1, fixed) - optimize_move_to_prewhere and query_plan_optimize_prewhere are
each randomized to False at p=0.05, and with both off pristine master returns the same 0 the fix
returns, so the new test silently stopped being a regression test in about one run in ten (both-ON
measured at 90.0% over 4000 draws of the real randomizer). Fixed with a per-setting clamp rather
than a blanket tag. The clamp fails silently on a wrong prefix, so it was verified through the runner's
own parser and with a negative control: with the prefix corrupted, 9 of 60 runs recorded a low draw
in query_log; with it correct, 0.

💡 Noted, not blocking - the three EXPLAIN actions = 1 arms are written against the pretty
plan renderer and do not pin explain_query_plan_default. It is not randomized and not forced by
any CI configuration, so there is no flake today, but the default did flip once (26.7) and 36 of
the 77 in-tree FROM (EXPLAIN actions tests pin it explicitly. A one-line SET would make them
default-flip-proof.

💡 Noted, not blocking - the new comment calls a created subquery set "frozen".
replaceSetAndKey can swap the whole SetAndKey, so that is marginally stronger than the code
guarantees; every writer of set_and_key->set runs before the set is created, where get() is
null and the readiness guard already declines, so no reachable state is affected.

Corrected during round 2: I first read arm 3 of the EXPLAIN block as a vacuous oracle,
reasoning that a table-backed set's action-node name is __set_<hash> and carries no table name.
That is true of the name but not of the rendering: formatSetPretty resolves a
FutureSetFromStorage to its StorageID, and it is reached only while the node is still a
function node. The arm is a positive assertion about the surviving function node and is the
strongest of the three.

Round-1 gate finding on link formatting was declined: the template's full-URL instruction governs
the relationship lines in its HTML comment block, which the body satisfies verbatim, while the
#116018 in the description is the rendered cross-reference.

Session id: cron:clickhouse-review-slot-8:20260824-062000

@clickhouse-gh clickhouse-gh Bot closed this Aug 24, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6dbaa58]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Bugfix validation (functional tests, amd64) ERROR
Bugfix validation (functional tests, aarch64) ERROR

AI Review

Summary

This PR fixes the empty-IN/ARRAY JOIN ILLEGAL_COLUMN mismatch by teaching FunctionIn when it may declare an empty-set constant and by keeping the runtime/header behavior aligned across tuple, subquery, and storage-backed sets. I did not find a live correctness bug in the current implementation, but the new regression test leaves one supported analyzer path unpinned.

Tests
  • ⚠️ tests/queries/0_stateless/05038_in_empty_set_array_join.sql:50 forces the new ENGINE = Set assertions at lines 57-61 onto enable_analyzer = 1, so the old-analyzer storage-backed ARRAY JOIN carrier this PR also fixes is no longer covered by the committed regression test. Add at least one focused enable_analyzer = 0 assertion for a IN t_in_empty_set_storage before switching analyzers or after switching back.
Final Verdict

⚠️ One important coverage gap remains: the committed test no longer proves the ENGINE = Set carrier under enable_analyzer = 0. I would add that focused old-analyzer assertion before merging.

LLVM Coverage Report

Measured on commit 6dbaa58.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 81.00% +0.10%

Changed lines: Changed C/C++ lines covered: 31/34 (91.18%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local, all-default settings, no server: the three statements from the issue return Code: 44 ILLEGAL_COLUMN on every invocation (fresh data path each run, asserting the literal error text rather than a non-zero exit). Not an intermittent flake.
b Root cause explained? Yes. FunctionIn disables the default constant-folding wrapper and folds by hand, but never declared the fold: for a built and empty set executeImpl returns a ColumnConst whatever the left operand is. With a non-constant left operand getFunctionArguments reports all_const = false, so tryFoldFunctionToConstant calls getConstantResultForNonConstArguments, which was not overridden and returned nullptr, leaving the DAG node non-constant, while ActionsDAG::updateHeader executes the function at input_rows_count = 0 and does obtain a ColumnConst. ARRAY JOIN rebuilds the block from the non-constant node, so the two headers are compared, blocksHaveEqualStructure fails, and makeConvertingActions throws. Verified from the tree that before #100226 the same branch returned a non-constant column, so both sides previously agreed.
c Fix matches root cause? Yes. It declares the missing fold at the single point where the two paths diverge, so both are computed by one predicate. Not a band-aid: setting ignore_constant_values = true at the generic ExpressionStep seam and materializing the constant inside ArrayJoinAction were both considered and rejected as symptom guards, as was reverting #100226's ordering (that would re-break the ConstantFilterDescription always-false exit the PR was written for).
d Test intent preserved / new tests added? Yes. New 05038_in_empty_set_array_join with 24 assertions covering both polarities, LEFT ARRAY JOIN, an explicit empty-array cast, a function-wrapped operand, multiIf, GLOBAL NOT IN, the not-ready and empty subquery sets, NULL semantics on Nullable and LowCardinality(Nullable), result types, and an ENGINE = Set table that is empty at planning time and non-empty afterwards. Both prewhere settings are pinned per setting (not with a blanket no-random-settings tag), because they are independently randomized to False at p=0.05 each, so the bug was armed in only 90% of runs, measured over 4000 draws of the randomizer; without the pin the test silently stops reproducing on about one run in ten, and with the pin in place it still reddens on pristine master. No existing test was weakened and no .reference anywhere in the tree needed updating.
e Both directions demonstrated? Yes. Same command: pristine master gives Code: 44, the patched binary gives 0. Confirmed twice over, once on the binaries directly and once on two live servers whose lower(buildId()) was asserted against readelf output. The new test's reference also differs from pristine master's output, so the test reddens without the fix.
f Fix is general across code paths? Yes. Enumerated all 24 functions that disable constant folding; in.cpp is the only one whose executeImpl can return a constant independent of a non-constant argument. notHas delegates to has and not and has no independent constant path (measured notHas([], a) returns 1 under ARRAY JOIN), neighbor gates its constant return on the source already being constant, and transform, castOrDefault and materialize were measured green. One override covers all eight registered variants because the guard reads the ignore_set, negative and result-type state rather than the function name.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Fifteen left-operand types return 0: Int8, UInt64 at its maximum, Float64, String, FixedString, Date, DateTime64, Decimal, UUID, Enum8, Array, Map, LowCardinality, Nullable and LowCardinality(Nullable). All four result-type wrappers are correct. Boundaries covered: empty table, empty array in the ARRAY JOIN, and a NULL row. Non-empty sets are correctly not folded (IN (7) returns 1, IN (999) returns 0).
h Backward compatible? (maintainer-approved exception only) Yes, nothing at risk. One source file, no new or changed setting, no SettingsChangesHistory.cpp row, no serialization or on-disk format change, no experimental gate. The old analyzer path (enable_analyzer = 0) is byte-identical on both binaries.
i Invariants and contracts preserved? Yes. The invariant added is that a built and empty set folds to the same ColumnConst that executeImpl produces, regardless of left-operand constness, and only when the result type carries no Nullable (because NULL IN () is NULL, not 0, so folding it would be a wrong-results bug; a mutation removing just that guard makes NULL IN () return 0, and only the two arms pinning NULL semantics move). executeImpl semantics are untouched, so FilterTransform::prepare(), ConstantFilterDescription and FilterDescription see an unchanged runtime shape. Every non-qualifying set state returns nullptr and is bit-identical to current behaviour. Readiness alone is not a sufficient contract: FutureSetFromSubquery::get() does return null unless the set is created, but FutureSetFromStorage::get() returns its set unconditionally and StorageSet::insertBlock grows that same object in place, so an ENGINE = Set table's current emptiness is not a property of the query. The fold therefore also requires the set kind to be immutable (a tuple set, or an already-created subquery set) and returns nullptr for anything else, which matches the planner's own refusal to treat a storage-backed set as deterministic. The emptiness check takes the set's own read lock, so it is safe while a set is being filled.

Session id: cron:clickhouse-impl-slot-7:20260823-214100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @KochetovNicolai, could you review this? FunctionIn disables the default constant-folding wrapper and folds by hand, but never declared the fold it performs, so for a built and empty set the DAG node stayed non-constant while ActionsDAG::updateHeader obtained a ColumnConst, and ARRAY JOIN forced the two headers to be compared. This adds the missing getConstantResultForNonConstArguments, folding only for an immutable set kind so an ENGINE = Set table that grows after planning is never folded.

The first version of this fix also folded an empty set that came from a
subquery. That is wrong: each shard runs index analysis against such a set and
reports it as a `0-element set` condition, which needs the `in` function to
still be present in the plan. Folding it to a constant collapsed the
`CreatingSets` subtree under `ReadFromRemote` and dropped the per-part index
analysis with it, which broke
03302_analyzer_distributed_filter_push_down.

Measured on unpatched master: only the tuple-set carrier throws ILLEGAL_COLUMN.
Eight subquery shapes (plain, GLOBAL IN, CTE, tuple key, in-place-built
primary-key sets, empty source table, numbers(0), transform_null_in) all
already return the correct result, so covering them bought nothing and cost the
index analysis.

FutureSetFromTuple is the only kind that qualifies: it runs insertFromColumns
and finishInsert in its constructor and never mutates the set afterwards. The
guard is written against that property rather than against literal `IN (...)`
syntax, because such sets are also built programmatically for runtime filters,
direct joins and Iceberg pruning.

The regression test gains a distributed arm that counts `0-element set` reports
for an empty subquery set. It reads 2 on master and on this commit, and 1 when
the subquery kind is folded.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 9df23c6: narrows the fold to tuple sets only.

The previous head also folded an empty subquery set, which broke 03302_analyzer_distributed_filter_push_down in Fast test. That test is right and the fold was wrong: each shard runs index analysis against such a set and reports Condition: (recordTimestamp in 0-element set), so the in function has to stay in the plan. Folding it collapsed the CreatingSets subtree under ReadFromRemote and took the per-part index analysis with it (Parts: 0/1 became Parts: 0/0).

Covering subquery sets also bought nothing. On unpatched master only the tuple-set carrier throws ILLEGAL_COLUMN; eight subquery shapes (plain, GLOBAL IN, CTE, tuple key, in-place-built primary-key sets, empty source table, numbers(0), transform_null_in) already return the correct result.

Verified on three servers with asserted buildId():

05038 (this fix) 03302
pristine master FAIL Code: 44 PASS
previous head FAIL FAIL
9df23c6 PASS PASS

The #65638 plan at 9df23c6 is byte-identical to pristine master's, so no reference was rewritten. The regression test gains a distributed arm counting 0-element set reports for an empty subquery set: 2 on master and on this commit, 1 if the subquery kind is folded.

The new_tests_check.py red was a cascade: both Bugfix validation functional arms were DROPPED behind the Fast test failure, so the check could not run. It should resolve now that Fast test is expected green; if it persists once the matrix runs I will treat it separately.

Comment thread src/Functions/in.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6dbaa58ac with master 6f9bea0cd (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

Three arms of the new test read the query plan, and two of them were
sensitive to configuration that CI randomizes.

The arm counting plan lines that name the `Set` table matched anywhere in
the plan. A `ReadFromRemoteParallelReplicas` step echoes the whole remote
query text, which also names the table, so the count read 2 instead of 1
whenever the read was distributed. It now matches the filter column line,
which is the line that carries the assertion. Measured on the shipped
binary and on pristine master: the old form read 1 without parallel
replicas and 2 with them, while the new form reads 1 in both. On a build
whose fold wrongly accepts a storage-backed set, the old form read 1
under parallel replicas, the value the reference expects, so it also
accepted a broken build.

The old analyzer folds an empty `Set` table into a constant, so the three
plan-shape arms describe the new analyzer only. They now pin
`enable_analyzer = 1`. Measured: with the pin the three arms report the
same values under both analyzers, and still separate the shipped binary
from pristine master and from a build that folds too much.

The distributed arm built its empty subquery set from
`remote(..., currentDatabase(), ...)`. The old analyzer forwards that
subquery to the shard as text, where `currentDatabase()` resolves to
`default` and the table is missing, so the query failed with
UNKNOWN_TABLE. The same failure reproduces with a non-empty set and on
pristine master, so it is a property of the shape rather than of the
fix. The set now comes from `numbers(0)`. The arm still counts one
per-shard index analysis report per shard, and still drops to one report
on a build that folds the subquery set away.

No reference file changed.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed e8ff7e2, which makes the three plan-shape assertions in 05038 independent of configuration that CI randomizes. Test file only, 6 lines, no reference rewritten.

05038 under ParallelReplicas. The arm counting plan lines that name the Set table matched anywhere in the plan, and a ReadFromRemoteParallelReplicas step echoes the whole remote query text, which also names the table. Measured on the shipped binary and on pristine master, with buildId() asserted on each server:

arm no parallel replicas with parallel replicas
old form 1 2
new form (filter column only) 1 1

Both binaries behave identically, so the arm was reading the environment rather than the fold. It also accepted a broken build: on a binary whose fold wrongly takes a storage-backed set, the old form read 1 under parallel replicas, exactly the value the reference expects.

05038 under the old analyzer. Two separate problems, both pre-existing and neither caused by the fix.

The distributed arm built its empty subquery set from remote(..., currentDatabase(), ...). The old analyzer forwards that subquery to the shard as text, currentDatabase() resolves to default there, and the table is missing. I reproduced the exact UNKNOWN_TABLE locally, then reran with a non-empty set (WHERE a > 0) and with the pristine master binary: it fails identically in both, so it is a property of the shape, not of the fold. The set now comes from numbers(0); the arm still counts one per-shard index analysis report per shard.

The old analyzer also folds an empty Set table into a constant, so all three plan-shape arms describe the new analyzer only. They now pin enable_analyzer = 1. With the pin the arms report the same values under both analyzers.

Both directions, via clickhouse-test. Shipped binary: 25/25 pass, and 15/15 with enable_analyzer=0. Pristine master 875331… and a binary that folds storage-backed sets both still FAIL, so the arms did not become blind:

arm line 49 line 50 line 51
pristine master 0 0 1
shipped fix 1 0 1
folds too much 1 1 0

Six failures in an unfiltered 25-run sweep were all one sandbox artifact: the runner drew cluster_for_parallel_replicas=parallel_replicas, whose replicas sit on port 9000, which nothing listens on in my sandbox. Forcing that draw gives Code: 371 on pristine master and on the mutated binary too.

AST fuzzer Block structure mismatch (STID 0993-2a62) is not from this PR. Over 30 days the signature has 4 occurrences on 4 unrelated PRs and none on master. #115264 is the decisive one: a fuzzer-only change, already merged, that touches no file in the const-fold path, and it hit the same STID with the same ARRAY JOIN plus NOT IN set shape and the same Const(size = 0) versus non-const mismatch. The reported query is a fuzzer mutation over merge('.*[0-9].*') FINAL with QUALIFY and an empty WINDOW, and the mismatch is raised in ArrayJoinStep::transformPipeline rather than in the IN function. Over 90 days the STID has 11 occurrences across 8 unrelated carriers and still no master row. It is owned by #115971, which reconciles sibling constness before uniting StorageMerge pipelines.

Gate B on the pushed content: 0 findings.

@fm4v
fm4v added this pull request to the merge queue Aug 26, 2026
@rschu1ze
rschu1ze removed this pull request from the merge queue due to a manual request Aug 26, 2026

@rschu1ze rschu1ze left a comment •

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.

IN is tricky. We should have @KochetovNicolai first have a look after his vacation if this PR is kosher. We are not in a hurry as the problem is an edge case that existed for a long time.

Comment thread src/Functions/in.cpp Outdated
if (ignore_set || arguments.size() != 2)
return nullptr;

/// A NULL left operand yields NULL whatever the set holds, so a Nullable result is not

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.

This looks strange. The comment talks about NULL left operands. The code checks if the result is a LowCardinality UInt8 type.

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.

You are right, the comment described only half of the test.

getReturnTypeImpl always returns UInt8, and the only wrappers IFunction adds are Nullable (from useDefaultImplementationForNulls, on for in and notIn) and LowCardinality. Measured, the reachable result types are exactly UInt8, LowCardinality(UInt8), Nullable(UInt8) and LowCardinality(Nullable(UInt8)), so isUInt8(removeLowCardinality(result_type)) means "the result is not Nullable": LowCardinality is stripped so a LowCardinality left operand keeps the fold, and Nullable is the case that must not fold. Both halves are pinned in the test, toTypeName(a IN ()) over a LowCardinality(String) column being LowCardinality(UInt8) and a NULL left operand giving NULL rather than 0.

Comment rewritten in fd830bb. I kept the positive spelling rather than isNullableOrLowCardinalityNullable because it fails closed: the constant below is built as static_cast<UInt8>(negative), so a return type that stops being UInt8 skips the fold instead of producing a wrong value. Happy to switch to the negative form if you prefer it.

Checking your point found a real gap next to it. executeImpl returned a ColumnConst for any empty set, so for the kinds the fold refuses the header was constant where the node was not, and an empty ENGINE = Set table under ARRAY JOIN still threw:

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

That is the same regression, not an older bug: correct on 26.3.23.2, Code: 44 on 26.7.6.15 and on master. Both paths now use one predicate (dc05735). I also corrected the description, which claimed only the tuple-set carrier throws on master; that was wrong.

Nothing further from me here until KochetovNicolai has had a look.

@fm4v

fm4v commented Aug 26, 2026

Copy link
Copy Markdown
Member

It was found during replay on 26.6 instance, so it should be merged as fast as possible

`getReturnTypeImpl` always returns `UInt8`, and the only wrappers `IFunction`
adds around it are `Nullable` (from `useDefaultImplementationForNulls`, which is
on for `in` and `notIn`) and `LowCardinality`. Measured, the reachable result
types are exactly `UInt8`, `LowCardinality(UInt8)`, `Nullable(UInt8)` and
`LowCardinality(Nullable(UInt8))`, so `isUInt8(removeLowCardinality(result_type))`
means "the result is not `Nullable`".

The old comment named only the `Nullable` half of that and so read as unrelated
to the `LowCardinality` term. Both halves are pinned by the test:
`toTypeName(a IN ())` over a `LowCardinality(String)` column is
`LowCardinality(UInt8)` and still folds, while a NULL left operand gives NULL
rather than 0.

The test is left in its positive form rather than spelled
`isNullableOrLowCardinalityNullable` because it fails closed: the constant below
is built as `static_cast<UInt8>(negative)`, so a return type that stops being
`UInt8` skips the fold instead of producing a wrong value.
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

The fix is complete from my side and CI is running on dc05735. v26.6-must-backport is already on the PR, so the 26.6 backport is produced automatically once it merges and nothing extra needs requesting.

Worth knowing for a 26.6 replay: the regression has a second carrier that this PR did not cover before dc05735. An empty ENGINE = Set table behaves the same way here as an empty list, so this threw Code: 44 as well:

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

Same window as the form you reported: correct on 26.3.23.2, Code: 44 on 26.7.6.15 and on master. Both are fixed now, and the test pins both.

The merge timing is not mine to decide. rschu1ze asked in his review above for KochetovNicolai, who wrote #100226, to check the approach first, so that is where the schedule sits.

…acked one

The previous commit narrowed the empty-set constant in executeImpl to a tuple
set, so that `a IN <ENGINE = Set table>` under ARRAY JOIN stops declaring a
constant in a step header while the DAG node stays non-constant. That also
dropped the constant for an empty subquery set, which is needed in two places:
FilterTransform::prepare() re-evaluates the filter through
ActionsDAG::updateHeader once the set is built and takes its always-false exit
from that constant, and the early return happens before the set arity is
checked.

Without it 01015_empty_in_inner_right_join read system.numbers up to the row
limit and stopped with TOO_MANY_ROWS, and
04545_correlated_subquery_in_set_speculative_build reported
NUMBER_OF_COLUMNS_DOESNT_MATCH for `i GLOBAL IN (SELECT '\0', i FROM ...)`
over an empty two-column set.

A subquery set holds no value while step headers are being declared, so a
constant reported after that cannot contradict one. Only a storage-backed set,
readable straight away and never folded, has to stay non-constant here. The
DAG-node fold is unchanged.
@groeneai

Copy link
Copy Markdown
Collaborator Author

The two Fast test failures on dc05735 were mine. ec671fbe fixes them.

dc05735 narrowed the empty-set constant in executeImpl to a tuple set, which also dropped it for an empty subquery set. FilterTransform::prepare() takes its always-false exit from that constant, and the early return happens before the set arity is checked, so 01015_empty_in_inner_right_join read system.numbers up to the row limit and 04545_correlated_subquery_in_set_speculative_build reported NUMBER_OF_COLUMNS_DOESNT_MATCH for an empty two-column set.

Now only a storage-backed set stays non-constant there, which is the kind the ENGINE = Set carrier needs. The DAG-node fold is unchanged. Both tests fail on dc05735 and pass on ec671fbe, and a 59-test sweep over the ENGINE = Set and empty-IN families shows no other verdict change.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Sorry for the delay. Merged master at 26604f639efc, which picks up #116566 (the revert of #109710). That was the Docs examples red: the known-failures baseline still named Function/catboostEvaluate#0 after CatBoost was removed, so nothing in this PR's own diff could clear it.

The merge preserves the change exactly, same three files and same patch-id. On the merged tree 05038_in_empty_set_array_join and the three pinned regression tests (01015_empty_in_inner_right_join, 04545_correlated_subquery_in_set_speculative_build, 03302_analyzer_distributed_filter_push_down) pass, 32 of 32 executions across 8 randomized runs.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f44965677e97c8f207eef1685f9c42484dc65c75

CI is fully finished on this head. Every failure below has an owner: a fixing PR (mine 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
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / Container memory budget exceeded (/docker) /docker cgroup leaf OOM kills the concurrent shutdown gdb attaches; job ERROR, no test failed #117202 (external, merged 2026-08-31), absent from this tree
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) same leaf OOM as above #117202 (external, merged 2026-08-31), absent from this tree; and since it does not clear 6/6, a fix task holds that residual and its fixing-PR link will be posted here when one opens
Performance Comparison (arm_release, master_head, 1/6) / Check Results (10 errors, 3 too long) one query aborted the shard: group_by_dynamic_keys query 0 raised Code: 159 Timeout exceeded: elapsed 329458 ms, maximum: 300000 ms, against a 3688 ms median and a 4229 ms 14-day maximum for that query on this shard, and aggregation_external was reported too slow to run a fix task is created (investigating at full effort, fixing-PR link to follow here)

None of the three is PR-caused. This PR changes ActionsDAG constant folding for an empty IN set
under ARRAY JOIN, plus its own stateless test.

On the two /docker rows: they are one signature, not two. The /docker cgroup leaf that bounds
the nested test containers is capped at 40.78 GiB and docker compose stop signals every node of a
cluster at once, so each node that outlives the 60 s deadline attaches gdb at the same moment; on
an ASan build each attach holds about 3.4 GiB of anonymous memory. #117202 serializes that attach.
It is merged, but it is outside the tree this run built: this head is a master merge from
2026-08-31 09:37:53Z, #117202 merged at 11:05:36Z, and compare reports the head diverged from
its merge commit 7fc3004ed25a. So the run predates the fix. I am not merging master here purely
to re-run CI, to keep the review load down. Measured caveat, stated so it is not a surprise later:
on master trees that DO contain #117202, 2/6 and 5/6 are clean (0 of 13 post-fix trees) but
6/6 still fires (13 of 13), and that residual is blocked on an owner decision about
integration-test capacity which I put to the maintainers at
#115963 (comment).

On the Performance Comparison row: perf.py raised the driver exception out of
execute_query_group rather than handling it, so the shard published errors instead of the other
560 or so measurements it had taken. It is not reachable from this diff: group_by_dynamic_keys
contains neither an IN set nor an ARRAY JOIN, and the report's own Test Performance Changes
table puts that test at -1.032x with Total not OK = 0. The single Changes in Performance row,
string_order_by #3 at +1.454x, appears under Unconfirmed Changes with a rerun relative
difference of -0.001 against a 0.004 threshold, so the rerun did not confirm it. Breadth over
the last 3 days on Performance Comparison (arm_release, master_head, *) is 13 reds across 10
unrelated PRs, every one of them carrying exactly 10 errors, against 5047 passing summary rows
over 533 PRs and 388 master runs; across all arches the daily count of such reds went from 1 to 7
per day earlier in the month to 56, 34 and 49 on 08-29, 08-30 and 08-31. #116491 (mine, open)
fixes the compare.sh pattern dialect that turns one failing test into ten error rows, and it is
deliberately not linked as the owner here because it provably does not turn the shard green.

Fast test, Style check, Bugfix validation, Config Workflow and Finish Workflow are all
OK on this head. PR and Check Results are praktika roll-ups: they report the rows above and
carry no separate defect.

Session id: cron:our-pr-ci-monitor:20260831-223000

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release, master_head, 1/6) shard abort: #117447

Comment on lines +50 to +61
SET enable_analyzer = 1;
SELECT count() FROM (EXPLAIN actions = 1 SELECT sum(b) FROM t_in_empty_set WHERE a IN ()) WHERE explain ILIKE '%Filter column: 0%';
SELECT count() FROM (EXPLAIN actions = 1 SELECT sum(b) FROM t_in_empty_set WHERE a IN t_in_empty_set_storage) WHERE explain ILIKE '%Filter column: 0%';
-- Only the filter column names the set: a `ReadFromRemote*` step echoes the whole remote query,
-- so an unscoped match counts a second line whenever the read is distributed.
SELECT count() FROM (EXPLAIN actions = 1 SELECT sum(b) FROM t_in_empty_set WHERE a IN t_in_empty_set_storage) WHERE explain ILIKE '%filter column:%' AND explain ILIKE '%t_in_empty_set_storage%';

SELECT count() FROM t_in_empty_set WHERE a IN t_in_empty_set_storage;
SELECT count() FROM t_in_empty_set ARRAY JOIN [b] AS x WHERE a IN t_in_empty_set_storage;
INSERT INTO t_in_empty_set_storage VALUES (1);
SELECT count() FROM t_in_empty_set WHERE a IN t_in_empty_set_storage;
SELECT count() FROM t_in_empty_set ARRAY JOIN [b] AS x WHERE a IN t_in_empty_set_storage;

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.

Pinning enable_analyzer = 1 is fine for the EXPLAIN shape checks, but because that setting stays in effect for lines 57-61, the new ENGINE = Set carrier this PR adds never executes under enable_analyzer = 0. The runtime fix in FunctionIn::executeImpl is shared by both analyzers, so the committed regression test no longer protects the old-analyzer ARRAY JOIN path for a IN t_in_empty_set_storage. Please add at least one old-analyzer output check for that carrier before this SET, or switch enable_analyzer back for a couple of assertions afterwards.

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.

Confirmed the structural half. The SET enable_analyzer = 1 above does stay in effect for the runtime checks below it, and the old-analyzer lane sets allow_experimental_analyzer = 0 only as a profile default (tests/config/users.d/analyzer.xml, linked by install.sh --analyzer), which an in-test SET overrides. Those lines always run under the new analyzer.

I am not adding the arm, because this defect is new-analyzer-only and an old-analyzer check for it cannot fail. Measured with clickhouse local on the issue fixture, query SELECT count() FROM t_in_empty_set ARRAY JOIN [b] AS x WHERE a IN t_in_empty_set_storage with the Set table still empty:

build enable_analyzer = 0 enable_analyzer = 1
pristine master 26.9.1.410 (dd7889a115c63e16) 0 Code: 44
this PR 0 0
this PR, canReportEmptySetAsConstant forced true 0 Code: 44

The third row is the sensitivity control: removing the guard this PR adds brings Code: 44 back under the new analyzer and leaves the old analyzer unchanged. After INSERT INTO t_in_empty_set_storage VALUES (1) every cell is 1, and the literal IN () carrier behaves the same way. So under enable_analyzer = 0 nothing separates pristine master, this PR, and this PR with its guard removed: the change is a measured no-op there, and the assertion you ask for would pin behaviour that no version of this code gets wrong.

Treating it as a nit for that reason. If a pre-fix old-analyzer reproducer for this shape does exist, I will add it as an arm.

pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Sep 1, 2026
…cheme

Follow-up for ClickHouse#110081, which moved build artifacts under the normalized workflow name: `REFs/master/<sha>/masterci/build_<bt>/clickhouse`. `find_master_builds` still probed the old `REFs/master/<sha>/build_<bt>/clickhouse` path, so once every commit in the `master_commits` window had only new-layout builds, both `Bugfix validation (functional tests)` jobs started failing with `AssertionError: Could not find master builds in S3` on every pull request, for example ClickHouse#116057.
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6dbaa58acfc2c84f8f0da5956bb01700c8cc1216

Every failure below has an owner: a fixing PR (mine 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
Bugfix validation (functional tests, amd64), Bugfix validation (functional tests, aarch64) harness abort before any test ran: assert build_urls, "Could not find master builds in S3" at ci/jobs/functional_tests.py:734. Master build artifacts moved under a normalized workflow-name prefix, so find_master_builds probes the old key and finds nothing. Trunk-wide: 91 distinct pull requests error against 2 passing, on each arch, in 24 h; this diff touches no ci/ file #117580 (external, merged 2026-09-01T22:06:23Z)
Finish Workflow / Post Hooks pure consequence of the two rows above: the failing child is new_tests_check.py, which enumerates both aborts #117580 (external, merged 2026-09-01T22:06:23Z)

I measured #117580 ABSENT from the tree that ran: the symbol it introduces has 0 occurrences at 6dbaa58acfc2 against 1 at its own merge commit 41b739a45086, with a pre-fix negative control at 0. The two jobs aborted at 20:42Z and the fix merged at 22:06Z, so this build predates it by about 84 minutes.

I have not merged master to pick it up. The current head is an empty CI-trigger commit pushed by the reviewer at 17:29Z and #117580 merged an hour later, so a re-trigger picks the fix up on a branch that is already being driven, and a master merge from me would only cost an extra full CI cycle.

Mergeable Check reports Failed: Workflow Post Hook, which is the consequence row above. Style check is success (0/15) and CH Inc sync is success, so nothing here is exempt. The table is the complete non-OK, non-SKIPPED node set of result_pr.json (172 nodes: 145 OK, 22 SKIPPED, 2 ERROR, 3 FAIL, the last of which includes the root PR node).

Session id: cron:our-pr-ci-monitor:20260901-230000

@fm4v
fm4v added this pull request to the merge queue Sep 2, 2026
Merged via the queue into ClickHouse:master with commit 38ee8b0 Sep 2, 2026
171 of 175 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 2, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 2, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 2, 2026
Backport #116057 to 26.8: Fix ILLEGAL_COLUMN for an empty IN set with ARRAY JOIN
clickhouse-gh Bot added a commit that referenced this pull request Sep 2, 2026
Backport #116057 to 26.7: Fix ILLEGAL_COLUMN for an empty IN set with ARRAY JOIN
@rschu1ze

rschu1ze commented Sep 2, 2026

Copy link
Copy Markdown
Member

@fm4v We made a fix, obviously without reviewing the code. Did we ever try to find out which PR introduced the regression (bisecting) so we could revert or fix it instead?

@fm4v

fm4v commented Sep 2, 2026

Copy link
Copy Markdown
Member

@rschu1ze yes, it's #100226

kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 10, 2026
Backport #116057 to 26.6: Fix ILLEGAL_COLUMN for an empty IN set with ARRAY JOIN
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Empty IN set with ARRAY JOIN throws ILLEGAL_COLUMN: in(...) non constant in source stream but must be constant in result

7 participants