Skip to content

Do not materialize a set operand for IgnoreSet functions in the planner - #122130

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:ignore-set-no-set-operand
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:ignore-set-no-set-operand

Conversation

@groeneai

@groeneai groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122042
Related: #120312

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

Not required: the crash was introduced on master by #120312 and has never been in a released version.

Description

inIgnoreSet and its seven siblings never read their right operand, returning 0 (NULL for a
null-skipping variant over a NULL operand); they exist to resolve types without building a set. Since #120312 the planner no longer registers a
set for them but still materializes a set operand, so that ActionsDAG column holds a null
pointer, which anything walking the plan then dereferences:

Both crash on current master, no special settings, no sanitizer:

SELECT count() FROM numbers(10) GROUP BY inIgnoreSet(number, (1, 2, 3));
SELECT count() FROM system.tables WHERE inIgnoreSet(name, ('no_such_table'));

Fix: do not build that operand, so an IgnoreSet call takes its left operand alone, the shape the
old analyzer already used (ActionsVisitor.cpp) and the reason FunctionIn is variadic (in.cpp).
The result type is unchanged, because getReturnType already counts a Set argument as constant.

One consumer reads that operand, so it is taught the new shape instead of guarded:
tryBuildAdditionalFilterAST rebuilds a shard-pushed filter as SQL text from the DAG's
children, so an IgnoreSet call is now declared non-convertible there, as lambdas already are.
Dropping that conjunct only widens what a shard returns.

#120312's access control is unaffected: neither PreparedSets lookup is reinstated, so the right
side is never prepared or authorized (test_set_engine_row_policy_serialized_plan passes).

The stateless test covers all eight variants, a lambda, EXPLAIN, PREWHERE, virtual-column and
remote-pushdown filters, wrapper types and plain-IN controls; red on master, green after.

Provenance: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=596f844fb392010d96a8a235a3275a002ee7ca38&name_0=MasterCI


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

groeneai and others added 3 commits September 24, 2026 23:31
The eight IgnoreSet variants of IN (in.cpp registers inIgnoreSet,
globalInIgnoreSet, notInIgnoreSet, globalNotInIgnoreSet, nullInIgnoreSet,
globalNullInIgnoreSet, notNullInIgnoreSet, globalNotNullInIgnoreSet) return 0
for every row without ever looking at their right operand. They exist so that
types can be resolved without building a set, and FunctionIn is variadic
precisely so the left operand can be passed alone: isVariadic() == ignore_set,
getNumberOfArguments() == ignore_set ? 0 : 2, and getReturnTypeImpl accepts 1 or
2 arguments and returns UInt8 either way (src/Functions/in.cpp:51-72). The old
analyzer already builds the node that way, and its comment at
src/Interpreters/ActionsVisitor.cpp:1322-1341 explains why a stand-in column is
not an acceptable substitute.

Commit c0596ea stopped preparing the right operand for these functions,
which is correct, but kept adding a set column to the ActionsDAG. It gated the
tuple lookup, the subquery/storage lookup and the guarding `if (!set) throw` on
!ignore_set, so `set` stays default-constructed and
ColumnSet::create(1, nullptr) enters the plan. That unconditional throw was what
enforced the invariant "a planner-built ColumnSet always holds a non-null
FutureSetPtr", so removing it turned an enforced property into an assumed one,
and every consumer that dereferences ColumnSet::getData() without a null check
became reachable with null. Six of the getData() call sites in the tree are in
that shape (ActionsDAG.cpp:4744, VirtualColumnUtils.cpp:83 and :140,
ReadFromRemote.cpp:324, KVStorageUtils.cpp:189 and :381); the rest null-check
the pointer before using it. Two were observed crashing within fifteen
minutes of each other on 2026-09-24, both first-ever in ninety days:

  - serializeConstant at src/Interpreters/ActionsDAG.cpp:4744, reached from the
    aggregation hash-table cache-key path
    (calculateHashTableCacheKeys.cpp:161 -> optimizeTreeSecondPass), master
    STID 2060-5018;
  - buildSetsForDagImpl at src/Storages/VirtualColumnUtils.cpp:84, reached from
    SourceStepWithFilterBase::applyFilters for virtual-column and PREWHERE
    filter analysis, STID 4168-5979.

Both are plain segmentation faults on a debug or release build, and UndefinedBehaviorSanitizer
reports them as a member call on a null pointer of type DB::FutureSet. Note
that this is a null shared_ptr, not the not-ready-set state, which is
future_set->get() == nullptr with future_set itself non-null.

Fix the producer rather than the consumers. visitFunction no longer calls
makeSetForInFunction for an IgnoreSet call and builds the DAG node from the left
operand alone, so no set column is created and there is nothing for a consumer
to dereference. Because makeSetForInFunction is no longer reached for these
functions, its ignore_set gates are removed and the unconditional
`if (!set) throw` is restored, which makes the invariant enforced again instead
of merely documented. Guarding the consumers was rejected: it is a symptom guard
at the dereference rather than a fix at the source, it does not scale, because
each consumer needs its own decision about what a null set means,
and serializeConstant has no good local answer because it must emit a
FutureSet::Hash, so a sentinel would silently collide distinct plans in the
hash-table statistics cache. Attaching a non-null empty placeholder set was also
rejected: notInIgnoreSet executes to 0, but an empty set makes a notIn predicate
true, so index analysis at KeyCondition.cpp:1044 and RPNBuilder.cpp:432 would
then disagree with execution.

Since the DAG node now has one child while the query tree function was resolved
over two arguments, the node is built from a FunctionFactory resolver over the
children that are actually present, which is the same branch group_by_use_nulls
already uses and which keeps the node's argument types in agreement with its
children.

The access-control behaviour added by c0596ea is unchanged: neither
PreparedSets lookup is reinstated, so the right-hand side is still never
prepared and never authorized, and
tests/integration/test_set_engine_row_policy_serialized_plan passes, including
the assertion that inIgnoreSet over a Set table succeeds for a user for whom the
plain IN spelling is denied by a row policy.

Co-Authored-By: Claude Opus 5 <[email protected]>
…r to a shard

tryBuildAdditionalFilterAST (src/Processors/QueryPlan/ReadFromRemote.cpp)
rebuilds a pushed-down filter as an AST out of the plan's expression DAG, and it
assumes the two-child shape for every IN-family function name. The previous
commit leaves an IgnoreSet call with its left operand alone, which breaks that
assumption in two independent ways.

The four global variants are covered by isNameOfGlobalInFunction
(src/Analyzer/Utils.cpp), so the GLOBAL IN block reaches node->children.at(1)
on a one-child node. std::out_of_range derives from std::logic_error, so
src/Common/Exception.cpp aborts the whole server process on a debug or
sanitizer build, and on any build where abort_on_logical_error is set
(observed: exit 134, stack through tryBuildAdditionalFilterAST); a release
build without that flag reports it as query error Code: 1001 instead. Either
way a query whose filter is pushed to a shard fails. Before the previous commit
this site was safe only incidentally, because the second child existed, its
FutureSetPtr was null, typeid_cast of a null pointer gave null, and the
set_from_subquery guard skipped the block.

The four local variants reach makeASTFunction with arguments built from
node->children, so the predicate is written back as one-argument SQL such as
HAVING inIgnoreSet(x). The receiving shard resolves that text and
src/Analyzer/Resolve/resolveFunction.cpp throws
NUMBER_OF_ARGUMENTS_DOESNT_MATCH for any isNameOfInFunction name, so the
distributed query fails.

Declare such a node non-convertible to AST instead, which is the mechanism this
function already uses for lambdas and for captures three lines above:
node_to_ast[node] = nullptr. Its existing handling then applies unchanged. The
parent's has_all_args goes false; an enclosing and() whose polarity is known
positive drops just that child, which is the invariant the function was
hardened for in ClickHouse#113445; and if the whole predicate is the IgnoreSet call the
function returns nullptr and addFilters adds no filter. This is sound because
the AST is only a pushdown optimization: omitting a conjunct can only widen
what the shard returns, the initiator still applies the whole filter, and an
IgnoreSet call evaluates to 0 for every row anyway, so no pruning is lost even
in principle.

The bail sits in the single argument walk that all three addFilters call sites
funnel through, so it covers the plain, the external-tables GLOBAL and the
parallel-replicas paths at once. It fires only when isNameOfInFunction accepts
the name and the name ends with IgnoreSet. isNameOfInFunction accepts sixteen
names, of which exactly eight end that way, so the walk is byte-identical in
behaviour for every DAG that contains no IgnoreSet call.

The regression test gains the remote arms, a plan-shape assertion that is true
only when the call has a single operand, a wrapper-type matrix whose output is
byte-identical to pristine master, an assertion that a filter mixing a
convertible conjunct with an IgnoreSet call still pushes the convertible one to
the shard, and a paired serialize_query_plan round trip over wrapped operands.

Co-Authored-By: Claude Opus 5 <[email protected]>
Condense the argument_types_match note to a one-line invariant: an IgnoreSet node has one child against two expected types.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Sep 25, 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; 6 findings over 3 rounds, the third
round clean), plus my own cold review of the resulting code each round (7 further findings, 1
withdrawn by me). Bounded: 1 full pass + fix rounds + delta recheck.

# Sev Finding Verdict Evidence / action
1 ❌ Dropping the set operand breaks distributed predicate pushdown for all eight variants (ReadFromRemote.cpp:428, :494) AGREE, fixed isNameOfGlobalInFunction covers the four global*IgnoreSet names, so children.at(1) was out of range; and the predicate was written back as one-argument SQL, which the shard rejects at resolveFunction.cpp:2342. tryBuildAdditionalFilterAST now treats an IgnoreSet node as non-convertible, the way it already treats lambdas. Forced-remote arms added for a local and a global variant.
2 ⚠️ The EXPLAIN assertion proved only that no crash happens, not that the operand is gone AGREE, fixed Every assertion in the file would have stayed green under a consumer-guard implementation. An EXPLAIN actions = 1 assertion now distinguishes the one-child node, verified green on the fix and red with the operand re-materialized.
3 ⚠️ No Nullable or LowCardinality left-operand coverage for the rebuilt node's result type AGREE, fixed The node is rebuilt through FunctionFactory, so the nullable and low-cardinality adaptors decide its type. Arms added for Nullable, LowCardinality, LowCardinality(Nullable) and both the null-skipping and null-comparing variants, with the output proven byte-identical to the pre-change binary.
4 ⚠️ The claim "13 of the 19 ColumnSet::getData() call sites would dereference null" AGREE, corrected Audited: six sites dereference the pointer with no null check; the rest check it, including seven I had listed as unguarded. A total depends on how multi-line reads of one site are grouped, so only the six is quoted: it is identical under every convention and is the only figure the argument uses.
5 💡 Nothing stated why a one-argument rebuild keeps the two-argument result type AGREE, fixed IFunctionOverloadResolver::getReturnType counts a Set argument as constant unconditionally, so the wrapper decisions are arity-independent. Said so in the description.
6 💡 Suggestion to drop the hunk that selects the factory resolver by arity DISAGREE ActionsDAG::deserialize rebuilds a function's base from its children's types and rejects a disagreeing serialized result type, and executeActionForPartialResult runs its argument-type-drift check only when the arities match, so without that hunk the check is silently skipped for these nodes. It also matches the old analyzer, which builds the node from a resolver over the single argument.
7 ⚠️ The remote arms could not tell "the IgnoreSet conjunct alone is dropped" from "the whole filter declines pushdown" AGREE, fixed All four arms assert results, and every result stays correct under selective degradation; the one liveness assertion explained a predicate with no IgnoreSet call in it. A liveness assertion on the combined x > 7 AND inIgnoreSet(...) predicate now pins that the convertible conjunct is still pushed, and is red under a mutation that declines the whole predicate.
8 ⚠️ Nothing round-tripped the one-child node through serialized query-plan deserialization AGREE, fixed ActionsDAG::deserialize rebuilds a function's base from its children and rejects a disagreeing result type, so the arity is load-bearing there, yet the pushdown arms have to set serialize_query_plan = 0 to reach the AST path at all. Paired serialize_query_plan = 1 / = 0 forced-remote arms added over a wrapped operand, in the oracle form 05059_serialize_query_plan_merge_source_column_names uses.
9 ⚠️ A commit message stated the std::out_of_range consequence without its build condition AGREE, corrected The abort is real and measured (exit 134, stack through tryBuildAdditionalFilterAST), but Exception.cpp aborts on a std::logic_error only under debug_or_sanitizer_build or abort_on_logical_error; a release build surfaces Code: 1001. The message now carries that condition.
10 💡 "Returns 0 for every row" contradicted the test's own Nullable reference rows AGREE, corrected The four null-skipping variants keep the default null wrapper, so a NULL left operand yields NULL; the 0-for-every-row statement describes executeImpl before that wrapper. Test comment and description both corrected.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding. Findings on hunks unchanged by the fix round are auto-dropped. One finding of my own,
that the global remote arm could not reach the out-of-range leg, I withdrew after re-reading the
signature: external_tables is a pointer, so that guard is a non-null test rather than an emptiness
test, and the committed global arm does cover the leg.

Round 3 was clean from both sides. My own cold re-derivation reached the same conclusions by
different routes: the regression's provenance (c0596ea47b450, merged the same day, which kept the
stand-in set column on the belief that the action builder required it, while the old analyzer had
already proved it does not); the arity-independence of getReturnType's LowCardinality and
Nullable decisions; and the fact that %Keys: inIgnoreSet(number)% reads the node's arity,
because the pretty plan printer renders a function from its children while the action node name
still carries the set key.

Noted, not blocking: on master the same null pointer also segfaults tryBuildAdditionalFilterAST
itself (getSourceAST() on it, exit 139, measured for all three pushdown predicates), so it is a
third crash site rather than only the two the description cites. That is an instance of the property
the description already states, so it did not buy a sentence.

Session id: cron:clickhouse-review-slot-10:20260924-234800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, three of them, each on 100% of runs on a plain debug build with default settings. SELECT count() FROM numbers(10) GROUP BY inIgnoreSet(number, (1,2,3)) segfaults (gdb stack matches the CI report frame for frame); SELECT count() FROM system.tables WHERE inIgnoreSet(name, ('x')) segfaults at a code-disjoint site; and an outer WHERE inIgnoreSet(...) or WHERE globalInIgnoreSet(...) over a remote() subquery segfaults at a third site, ReadFromRemote.cpp:324 in tryBuildAdditionalFilterAST, which calls getSourceAST() on the null FutureSetPtr. The exit 134 std::out_of_range abort recorded for that last query was measured on this PR's own first commit, where the node has one child; pristine master segfaults there instead.
b Root cause explained? Yes. IgnoreSet name -> the planner skips the set lookup and the guarding if (!set) throw -> ColumnSet::create(1, nullptr) is still added to the ActionsDAG -> any consumer calling getData()->... dereferences a null FutureSetPtr. Introduced by c0596ea47b450c (#120312, merged 2026-09-24T13:04:51Z); first sighting 2h46m later, 90 days clean before. It is a null shared_ptr, not the "not-ready set" state.
c Fix matches root cause? Yes, fixed at the producer: no operand is materialized for a call that never reads one, and the unconditional if (!set) throw is restored so the invariant is enforced mechanically again. No consumer is null-guarded. The one consumer file edited is a shape adaptation rather than a guard: tryBuildAdditionalFilterAST rebuilds a pushed-down filter as SQL text from the DAG's children, so a call with no set operand is declared non-convertible to AST, exactly as that function already treats lambdas and captures.
d Test intent preserved / new tests added? New stateless test 05255_in_ignore_set_without_set_operand, 26 assertion queries. No existing test weakened: no assertion widened, no dataset reduced, no no-random-* tag added, and the earlier reference lines are a byte-identical prefix of the current file.
e Both directions demonstrated? Yes. 15-arm matrix: 12 arms rc=139 without the fix, all rc=0 with it, 3 controls unchanged. The test was observed killing the unfixed server (exit 139, Address: NULL pointer, ActionsDAG.cpp:4744, attributed by log_comment). For the pushdown path: pristine master segfaults at ReadFromRemote.cpp:324, this PR's first commit alone gives Code: 42 NUMBER_OF_ARGUMENTS_DOESNT_MATCH or an exit 134 abort, and the finished change returns 0. The serialized-plan arms segfault pristine master at ActionsDAG.cpp:4744 through FilterStep::serialize and agree at 0 with the fix. Four mutation builds, each deleting or inverting one part of the change and confirming the corresponding arms go red again.
f Fix is general across code paths? Yes. Six ColumnSet::getData() call sites dereference the result without a null check, and the producer fix closes all six at once while editing none of them. Two were independently observed crashing in master CI (ActionsDAG.cpp:4744, VirtualColumnUtils.cpp:83), and a third, ReadFromRemote.cpp:324, was measured segfaulting pristine master here. The pushdown adaptation sits in the single argument walk that all three addFilters call sites funnel through, so it covers the plain, the GLOBAL/external-tables and the parallel-replicas paths at once. Two unrelated null-ColumnSet producers that pre-date #120312 by years reach no serialized or optimized DAG and are deliberately left alone.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, asserted in the test: all 8 IgnoreSet variants, locally and through a remote pushdown; left operands plain, Nullable, LowCardinality, LC(Nullable), Array, Map, Tuple, Const, NULL; right operands tuple, empty tuple, subquery; plus group_by_use_nulls = 1, and a paired serialize_query_plan = 1/0 distributed round trip over LowCardinality and Nullable operands (8 operand types were additionally round-tripped by hand). Type and value are now read back across the aggregation boundary, and that wrapper matrix is byte-identical to pristine master.
h Backward compatible? Yes. No setting added or changed, so no SettingsChangesHistory.cpp entry; no format change. One fewer constant node is emitted for a function that never read it, and the aggregation cache key changes only for queries that previously crashed, so no versioning gate is needed. Every behaviour change is confined to the eight *IgnoreSet names, which have never been in a release. #120312's access-control behaviour is preserved: neither PreparedSets lookup is reinstated, and test_set_engine_row_policy_serialized_plan passes.
i Invariants and contracts preserved? The restored invariant is the one #120312 dropped: a ColumnSet reachable from a planner-built ActionsDAG always holds a non-null FutureSetPtr, now enforced on every path through makeSetForInFunction. Arity contract holds: an in-function is resolved with exactly two arguments (resolveFunction.cpp:2342), and FunctionIn accepts 1 or 2 by design, returning UInt8 either way (in.cpp:51-72). In the pushdown walk, node_to_ast[node] = nullptr is that function's own documented "not convertible" signal, already handled by has_all_args, by conjuncts_safe_to_drop and by the nullptr return; the polarity invariant added in #113445 still holds, so a conjunct is dropped only where the polarity is known positive and otherwise nothing is pushed at all. Omitting a conjunct can only widen what a shard returns, and the initiator still applies the whole filter. The lambda-capture path is exercised and returns [0,0] without throwing.

Session id: cron:clickhouse-impl-slot-4:20260924-231505

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [302ee40]


AI Review

Summary

This PR fixes the null ColumnSet dereference by stopping planner-side set materialization for *IgnoreSet functions and by teaching remote-filter reconstruction not to serialize those nodes back as IN. That local/serialized-plan shape change looks sound, but the distributed GLOBAL path still materializes a subquery/table right operand for global*IgnoreSet, so the promised "ignore the right operand entirely" contract is still broken there.

Findings

❌ [src/Storages/buildQueryTreeForShard.cpp:419-426, 1000-1023] GLOBAL ... IgnoreSet still executes/materializes its right-hand subquery or table on distributed queries. getGlobalInFunctionNameForLocalInFunctionName can rewrite a local *IgnoreSet to a global one under distributed_product_mode = global, and the later global_in_or_join_nodes loop still unconditionally runs executeSubqueryNode for QUERY/UNION/TABLE right operands. That violates the function contract this PR relies on: a query whose *IgnoreSet predicate should be a constant false/NULL filter can still do real work and can still fail on permission or transfer-limit errors from an operand the function never reads.
Suggested fix: exclude the IgnoreSet variants from the global-IN rewrite/materialization path in buildQueryTreeForShard, and add a distributed regression test whose right operand is a subquery or table rather than only a constant tuple.

Final Verdict

❌ Changes requested. The planner/DAG fix is correct for the local plan shape, but the distributed GLOBAL rewrite still reads the supposedly ignored operand.


/// The `IgnoreSet` variants resolve types without a set: no set is registered for them, and they
/// take the left operand alone, which `FunctionIn`'s variadic arity accepts.
const bool ignore_set = is_in_function && function_node.getFunctionName().ends_with("IgnoreSet");

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.

Skipping the set child here does not complete the *IgnoreSet-never-reads-its-right-operand contract for distributed queries. buildQueryTreeForShard still treats global*IgnoreSet like ordinary GLOBAL IN: the distributed_product_mode = global rewrite keeps the IgnoreSet names in play at src/Storages/buildQueryTreeForShard.cpp:419-426, and the later global_in_or_join_nodes loop still unconditionally executes/materializes a QUERY/UNION/TABLE second argument at src/Storages/buildQueryTreeForShard.cpp:1000-1023. That means GLOBAL ... IgnoreSet over a subquery/table can still do real work and still fail on access or transfer-limit errors from an operand the function result ignores.

Can we exclude the IgnoreSet variants from that rewrite/materialization path too, and cover it with a distributed test whose RHS is a subquery or table rather than only a constant tuple?

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 302ee4059 with master c68449eaa (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

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

Job report

alexey-milovidov pushed a commit that referenced this pull request Sep 25, 2026
The eight IgnoreSet variants of IN (in.cpp registers inIgnoreSet,
globalInIgnoreSet, notInIgnoreSet, globalNotInIgnoreSet, nullInIgnoreSet,
globalNullInIgnoreSet, notNullInIgnoreSet, globalNotNullInIgnoreSet) return 0
for every row without ever looking at their right operand. They exist so that
types can be resolved without building a set, and FunctionIn is variadic
precisely so the left operand can be passed alone: isVariadic() == ignore_set,
getNumberOfArguments() == ignore_set ? 0 : 2, and getReturnTypeImpl accepts 1 or
2 arguments and returns UInt8 either way (src/Functions/in.cpp:51-72). The old
analyzer already builds the node that way, and its comment at
src/Interpreters/ActionsVisitor.cpp:1322-1341 explains why a stand-in column is
not an acceptable substitute.

Commit c0596ea stopped preparing the right operand for these functions,
which is correct, but kept adding a set column to the ActionsDAG. It gated the
tuple lookup, the subquery/storage lookup and the guarding `if (!set) throw` on
!ignore_set, so `set` stays default-constructed and
ColumnSet::create(1, nullptr) enters the plan. That unconditional throw was what
enforced the invariant "a planner-built ColumnSet always holds a non-null
FutureSetPtr", so removing it turned an enforced property into an assumed one,
and every consumer that dereferences ColumnSet::getData() without a null check
became reachable with null. Six of the getData() call sites in the tree are in
that shape (ActionsDAG.cpp:4744, VirtualColumnUtils.cpp:83 and :140,
ReadFromRemote.cpp:324, KVStorageUtils.cpp:189 and :381); the rest null-check
the pointer before using it. Two were observed crashing within fifteen
minutes of each other on 2026-09-24, both first-ever in ninety days:

  - serializeConstant at src/Interpreters/ActionsDAG.cpp:4744, reached from the
    aggregation hash-table cache-key path
    (calculateHashTableCacheKeys.cpp:161 -> optimizeTreeSecondPass), master
    STID 2060-5018;
  - buildSetsForDagImpl at src/Storages/VirtualColumnUtils.cpp:84, reached from
    SourceStepWithFilterBase::applyFilters for virtual-column and PREWHERE
    filter analysis, STID 4168-5979.

Both are plain segmentation faults on a debug or release build, and UndefinedBehaviorSanitizer
reports them as a member call on a null pointer of type DB::FutureSet. Note
that this is a null shared_ptr, not the not-ready-set state, which is
future_set->get() == nullptr with future_set itself non-null.

Fix the producer rather than the consumers. visitFunction no longer calls
makeSetForInFunction for an IgnoreSet call and builds the DAG node from the left
operand alone, so no set column is created and there is nothing for a consumer
to dereference. Because makeSetForInFunction is no longer reached for these
functions, its ignore_set gates are removed and the unconditional
`if (!set) throw` is restored, which makes the invariant enforced again instead
of merely documented. Guarding the consumers was rejected: it is a symptom guard
at the dereference rather than a fix at the source, it does not scale, because
each consumer needs its own decision about what a null set means,
and serializeConstant has no good local answer because it must emit a
FutureSet::Hash, so a sentinel would silently collide distinct plans in the
hash-table statistics cache. Attaching a non-null empty placeholder set was also
rejected: notInIgnoreSet executes to 0, but an empty set makes a notIn predicate
true, so index analysis at KeyCondition.cpp:1044 and RPNBuilder.cpp:432 would
then disagree with execution.

Since the DAG node now has one child while the query tree function was resolved
over two arguments, the node is built from a FunctionFactory resolver over the
children that are actually present, which is the same branch group_by_use_nulls
already uses and which keeps the node's argument types in agreement with its
children.

The access-control behaviour added by c0596ea is unchanged: neither
PreparedSets lookup is reinstated, so the right-hand side is still never
prepared and never authorized, and
tests/integration/test_set_engine_row_policy_serialized_plan passes, including
the assertion that inIgnoreSet over a Set table succeeds for a user for whom the
plain IN spelling is denied by a row policy.

Co-Authored-By: Claude Opus 5 <[email protected]>

(cherry picked from commit 19d4854 of #122130)
alexey-milovidov pushed a commit that referenced this pull request Sep 25, 2026
…r to a shard

tryBuildAdditionalFilterAST (src/Processors/QueryPlan/ReadFromRemote.cpp)
rebuilds a pushed-down filter as an AST out of the plan's expression DAG, and it
assumes the two-child shape for every IN-family function name. The previous
commit leaves an IgnoreSet call with its left operand alone, which breaks that
assumption in two independent ways.

The four global variants are covered by isNameOfGlobalInFunction
(src/Analyzer/Utils.cpp), so the GLOBAL IN block reaches node->children.at(1)
on a one-child node. std::out_of_range derives from std::logic_error, so
src/Common/Exception.cpp aborts the whole server process on a debug or
sanitizer build, and on any build where abort_on_logical_error is set
(observed: exit 134, stack through tryBuildAdditionalFilterAST); a release
build without that flag reports it as query error Code: 1001 instead. Either
way a query whose filter is pushed to a shard fails. Before the previous commit
this site was safe only incidentally, because the second child existed, its
FutureSetPtr was null, typeid_cast of a null pointer gave null, and the
set_from_subquery guard skipped the block.

The four local variants reach makeASTFunction with arguments built from
node->children, so the predicate is written back as one-argument SQL such as
HAVING inIgnoreSet(x). The receiving shard resolves that text and
src/Analyzer/Resolve/resolveFunction.cpp throws
NUMBER_OF_ARGUMENTS_DOESNT_MATCH for any isNameOfInFunction name, so the
distributed query fails.

Declare such a node non-convertible to AST instead, which is the mechanism this
function already uses for lambdas and for captures three lines above:
node_to_ast[node] = nullptr. Its existing handling then applies unchanged. The
parent's has_all_args goes false; an enclosing and() whose polarity is known
positive drops just that child, which is the invariant the function was
hardened for in #113445; and if the whole predicate is the IgnoreSet call the
function returns nullptr and addFilters adds no filter. This is sound because
the AST is only a pushdown optimization: omitting a conjunct can only widen
what the shard returns, the initiator still applies the whole filter, and an
IgnoreSet call evaluates to 0 for every row anyway, so no pruning is lost even
in principle.

The bail sits in the single argument walk that all three addFilters call sites
funnel through, so it covers the plain, the external-tables GLOBAL and the
parallel-replicas paths at once. It fires only when isNameOfInFunction accepts
the name and the name ends with IgnoreSet. isNameOfInFunction accepts sixteen
names, of which exactly eight end that way, so the walk is byte-identical in
behaviour for every DAG that contains no IgnoreSet call.

The regression test gains the remote arms, a plan-shape assertion that is true
only when the call has a single operand, a wrapper-type matrix whose output is
byte-identical to pristine master, an assertion that a filter mixing a
convertible conjunct with an IgnoreSet call still pushes the convertible one to
the shard, and a paired serialize_query_plan round trip over wrapped operands.

Co-Authored-By: Claude Opus 5 <[email protected]>

(cherry picked from commit 64f2f5b of #122130)
alexey-milovidov pushed a commit that referenced this pull request Sep 25, 2026
Condense the argument_types_match note to a one-line invariant: an IgnoreSet node has one child against two expected types.

(cherry picked from commit 302ee40 of #122130)
@alexey-milovidov

Copy link
Copy Markdown
Member

Thank you! #120312 was reverted in #122140, and the commits of this PR are incorporated (with authorship preserved) into the reapplying PR #122141, so the change and its fix land together. Closing this one in favor of #122141.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, that lands better than merging mine on its own.

I verified #122141 carries my three commits byte for byte with authorship intact, including the regression test 05255_in_ignore_set_without_set_operand. I will follow #122141 and leave this one closed.

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-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Server crashes with SIGSEGV on inIgnoreSet in a WHERE/PREWHERE filter

2 participants