Skip to content

Do not merge an equality chain into IN when the set cannot be built - #121196

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:do-not-merge-chain-into-unbuildable-in
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:do-not-merge-chain-into-unbuildable-in

Conversation

@groeneai

@groeneai groeneai commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121146 (comment)

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):

Three or more OR-ed equality comparisons on a Variant column whose alternative is an Array or a Tuple were merged into an IN whose set cannot be built, so the query was rejected with Unsupported types for IN while one comparison and a raised optimize_min_equality_disjunction_chain_length both answered it. The merge is now skipped for such a pair.

Description

Whether a query is accepted must not depend on an optimizer threshold. On master at defaults:

SELECT count() FROM (SELECT CAST([toInt64(number)], 'Variant(Array(Int64))') AS v FROM numbers(10))
WHERE v = [toInt64(1)] OR v = [toInt64(2)] OR v = [toInt64(3)];   -- Code: 43

One term answers 1, and these three answer 3 at threshold 100. Variant(Tuple(Int64)) too.

Root cause: getSetElementsForConstantValue decides by nesting depth whether the constant is the list of members or one value, and getCompoundTypeDepth descends Array and Tuple but not Variant. The pass builds the right-hand side from the literals' own types, so Variant(Array(Int64)) measures 0 against the tuple's 2, no branch matches, and the terminal throw fires at planning time.

I decline the rewrite at both chain-to-IN seams when a literal does not sit at the expression's own depth, through a predicate exported from SetUtils rather than a copy of its arithmetic. convertNotEqualsChainToNotIn is guarded for symmetry with the hasDynamicStructure() screen beside it, though that seam is measurably inert here. The other passes that build an IN from constants cannot reach such a pair; I read both.

I did not widen IN instead: on Variant(Array(Date), Array(UInt64)) a hand-written IN answers 0 where = answers 1, so admitting more pairs would turn an explicit error into silent wrong results.

One shape changes: requiring every literal at that depth is stricter than the set builder, which looks only at the first, so v = 1 OR v = [2] OR v = 3 on Variant(Int64, Array(Int64)) answered 2 by silently dropping the unconvertible member and now raises the error the unmerged chain already raises. Making it answer needs the set path to carry a Variant discriminator, a separate defect. Say the word and I will fold that in.


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

Three or more OR-ed equality comparisons on a Variant expression whose
alternative is an Array or a Tuple were merged into an `in` whose set
`getSetElementsForConstantValue` cannot place, so the query was rejected with
`Unsupported types for IN` while one comparison and a raised
`optimize_min_equality_disjunction_chain_length` both answered it. Whether the
query is accepted therefore depended on how many comparisons were conjoined.

`getSetElementsForConstantValue` decides by nesting depth whether to read the
constant right-hand side as the list of set members (depths differ by one), as
one whole value (depths equal), or neither, in which case it throws.
`getCompoundTypeDepth` unwraps Nullable and descends Array and Tuple but not
Variant, and the pass writes the literals with the alternative's type rather
than the Variant's, so `Variant(Array(Int64))` measures 0 against the built
`Tuple(Array(Int64), ...)`'s 2 and no branch matches. The throw fires at
planning time from CollectSets, not while the pass runs, so `EXPLAIN QUERY
TREE` succeeds and the pass cannot detect the failure by resolving the node: a
predicate is required.

Both chain-to-`in` seams now decline when any literal does not sit at the
expression's own depth, asking a predicate exported from SetUtils rather than
restating the depth rules in the pass. Declining hands the chain back to the
comparisons it was built from, so the outcome becomes the unmerged chain's own:
the correct answer for the shapes above, and, for the one mixed-depth shape
described below, the error that chain already raises. The notEquals seam is
guarded for symmetry with the `hasDynamicStructure()` screen beside it even
though it is measurably inert for this shape at default settings.

Widening the set builder instead was refuted by measurement: on a
`Variant(Array(Date), Array(UInt64))` column a hand-written `IN` already
answers 0 where `=` answers 1, because a set element is rebuilt from a Field
that carries no discriminator, so admitting more Variant pairs would replace an
explicit error with silent wrong results. That faithfulness defect is separate
and has to land first.

Requiring every literal at the expression's depth is stricter than the set
builder, which looks only at the first element. One shape changes as a result:
`v = 1 OR v = [2] OR v = 3` on `Variant(Int64, Array(Int64))` answered 2 by
silently dropping the unconvertible member, and now raises, verbatim, the same
`Illegal types of arguments ... of function equals` the unmerged chain raises.
The test asserts that error, so the change is pinned rather than only described.
The alternative, a first-element-only screen, would decline
`v = [1] OR v = 2 OR v = 3` and admit `v = 2 OR v = [1] OR v = 3`, and that
same test row is what fails under it.

A hand-written `IN` on the affected shape is unchanged and still throws.

Related: ClickHouse#121146 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 20, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; 0 findings in both rounds) plus a
separate cold read of the resulting code, which raised 6 across two rounds (bounded: 1 full pass +
1 fix round + 1 delta recheck). All 6 are AGREE; nothing was overridden.

# Sev Finding Verdict Evidence / action
1 ⚠️ The one behaviour change outside this PR's contract was untested: requiring every literal at the expression's depth is stricter than the set builder, which dispatches on the first tuple element only (src/Analyzer/SetUtils.cpp:48-83), so v = 1 OR v = [2] OR v = 3 on Variant(Int64, Array(Int64)) answered 2 and now raises ILLEGAL_TYPE_OF_ARGUMENT. Nothing pinned it, and a first-element-only variant keeps all 7 other new rows green. AGREE, fixed @ d4e3e4b9 One { serverError ILLEGAL_TYPE_OF_ARGUMENT } row, zero reference churn. Live in both directions: on revert the query answers 2, and under a first-element-only screen it also answers 2, where a diff of the observed output against the reference is that single line, so this row is the only thing that catches it.
2 💡 src/Analyzer/SetUtils.h claimed the set builder "decides that by nesting depth alone"; in the equal-depth branch it also inspects the constant's contents and may read it as a set of elements rather than one member (SetUtils.cpp:756-826). AGREE, fixed @ d4e3e4b9 Reworded in place to the narrower invariant the two call sites actually rely on, still 2 lines.
3 💡 The convertNotEqualsChainToNotIn guard is unreachable for every constructible type: Variant is the only type whose depth can mismatch a literal's, and that seam discards a Variant chain at its own nullable early return. AGREE, not blocking Kept deliberately: it mirrors the hasDynamicStructure() screen present at both seams, and the description states the inertness. No test is owed, since any row would be vacuous.
4 💡 getCompoundTypeDepth on the expression type is recomputed once per literal. AGREE, not blocking Negligible next to the per-literal tryConvertToColumnType beside it; hoisting would change the helper's signature for a few typeid_casts.
5 ⚠️ The draft description asserted that declining a rewrite "can only forgo a fold, never change an answer" two paragraphs above its own disclosure that one shape now raises an error instead of answering 2. AGREE, fixed before publication False sentence removed from the description, and from the commit message, which made the same claim. No code affected.
6 💡 The new row can assert the error code but not the message, and the set builder's own Unsupported types for IN is also ILLEGAL_TYPE_OF_ARGUMENT, so the row pins the outcome rather than which path produced it. AGREE, no action A stateless test cannot match a message, both realistic mutations make the query succeed rather than raise, and the EXPLAIN QUERY TREE row already pins the decline itself.

Verified against the code rather than assumed:

  • both consumers of the set builder pass the expression's raw result type, which is what the new predicate measures, and the pass hands the in that same node;
  • Variant is genuinely missed by the existing hasDynamicStructure() screen, so the predicate is load-bearing;
  • equal-depth literals always build a tuple exactly one level deeper, so the guard cannot admit an unplaceable pair;
  • tryConvertToColumnType takes the literal by const pointer and returns a Field, so the type the guard reads is the one that lands in the tuple;
  • the sibling passes that build an IN from constants (RewriteHasToInPass, InverseDictionaryLookupPass, the EXISTS rewrite) cannot reach such a pair;
  • no LowCardinality fold is lost: LowCardinality(Array(...)) and LowCardinality(Tuple(...)) are unconstructible (DataTypeLowCardinality.cpp:37, and neither type overrides canBeInsideLowCardinality()).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding; there are none here.

Session id: cron:clickhouse-review-self-slot-58:20260920-140800

@clickhouse-gh clickhouse-gh Bot closed this Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM (SELECT CAST([toInt64(number)], 'Variant(Array(Int64))') AS v FROM numbers(10)) WHERE v = [toInt64(1)] OR v = [toInt64(2)] OR v = [toInt64(3)] raises Code: 43 Unsupported types for IN every time on master, no non-default setting.
b Root cause explained? Yes. getSetElementsForConstantValue picks its branch by nesting depth; getCompoundTypeDepth does not descend Variant, so Variant(Array(Int64)) measures 0 against the pass-built Tuple(Array(Int64), ...)'s 2, no branch matches, and the terminal throw fires at planning time (SetUtils.cpp:849 from CollectSets.cpp:95, confirmed by stack trace).
c Fix matches root cause? Yes. The pass stops building an IN the set builder cannot place, asking the module that owns the depth arithmetic. No widened bound, no no-random tag, no guard at the throw site. Teaching getCompoundTypeDepth to descend Variant was refuted by measurement: on Variant(Array(Date), Array(UInt64)) a hand-written IN answers 0 where = answers 1, so it would turn an explicit error into silent wrong results.
d Test intent preserved / new tests added? Yes. Purely additive to the existing 04628_logical_optimizer_in_rewrite_variant_type; its 44 existing reference lines are untouched and still pass. The new rows keep all three oracle kinds: behaviour rows that survive a future real fix, plan rows that redden under a blanket exclude Variant guard, and one { serverError ILLEGAL_TYPE_OF_ARGUMENT } row pinning the single behaviour change outside the fix, so it is asserted rather than only described.
e Both directions demonstrated? Yes, three times. Base 688ee332 vs fix build 5967a78e across 45 shapes; a mutation probe with only the pass hunk reverted (build 5cff2d44, SetUtils helper kept) is [ FAIL ] return code 43; and a second mutation modelling a first-element-only screen (build dd05ad22) reddens the error row alone, its observed output differing from the reference by exactly one line.
f Fix is general across code paths? Yes. Both chain-to-IN seams guarded. The two other in-tree in-building passes were read and shown structurally unable to reach it: RewriteHasToInPass returns for any nullable or compound needle and separately requires the element and needle types to be equal; InverseDictionaryLookupPass builds Array(T) exactly one level above its key expression, or an IN (SELECT ...) subquery that never calls the set builder.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 45 shapes A/B: Nullable(Tuple), LowCardinality, Array, Tuple, Map, Enum, Array(Array), Array(Tuple), Tuple(Tuple), single- and multi-alternative Variant, Dynamic, JSON, chain lengths 1/2/3/4, the Int64 maximum, an empty-array literal, and the transform_null_in / use_variant_default_implementation_for_comparisons matrix. 7 shapes go from Code: 43 to the correct answer; 1 is the disclosed incidental decline; every other shape is identical on both arms. Wrapper combinations that do not exist (Nullable(Array), Nullable(Variant), LowCardinality(Array)) were shown unconstructible rather than skipped.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or changed, so no SettingsChangesHistory.cpp entry; IN itself is untouched, so nothing hand-written changes; no format change. The one change beyond the fix is the mixed-depth decline stated in the description, which replaces an error-masking answer with the error the unmerged chain already raises.
i Invariants and contracts preserved? Yes. The flag accumulates in the loop that already accumulates the tuple arguments, with no break, so the screen is order-independent. On decline the code takes the existing decline path unchanged, which runs before the ConstantNode and FunctionNode are built: no partially built node, no moved-from read, no resolution side effect. Nothing touches locking, block structure or sort order, and the pass holds no cross-query state.

Session id: cron:clickhouse-impl-self-slot-57:20260920-134600

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e259375]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
read_in_reverse_order_final #0 FAIL dashboard
read_in_reverse_order_final #1 FAIL dashboard
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
array_first_last #11 FAIL dashboard

AI Review

Summary

This PR teaches the logical-expression optimizer to skip OR/AND chain rewrites into IN/NOT IN when a Variant-wrapped Array or Tuple literal would make the constant set unbuildable, so query acceptance no longer depends on optimize_min_equality_disjunction_chain_length. I did not find remaining correctness or coverage issues in the current branch, and the earlier legacy-mutation concern is obsolete now that the old analyzer path is normalized away in executeQuery (src/Interpreters/executeQuery.cpp:2306-2313).

Final Verdict

✅ No blocking issues found in the current diff.

LLVM Coverage Report

Measured on commit e259375.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 27/28 (96.43%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit e2593751d9c10d30eb433f8d4dc6ccdddee8b495 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9c7ca2f

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
Build profile diff infra, the CI logs cluster refuses the read (ci/jobs/build_profile_diff_job.py traceback); 342 red rows over 294 PRs in 24h, 0 on master, and no re-run clears it #121048 (external, open)

The red PR status is the praktika rollup of the row above; it carries no failure of its own.

CIDB carries zero FAIL/ERROR test rows at this sha, and the dedupped check-run census is
172 green or skipped against the one red above.

Session id: cron:our-pr-ci-monitor:20260921-000159

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants