Skip to content

Fix LOGICAL_ERROR in set skip index when predicate is Nullable but granule is not - #110338

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-set-index-nullable-return-type-89802
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-set-index-nullable-return-type-89802

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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 a LOGICAL_ERROR ("Unexpected return type from ...") when a query filters on a set skip-index expression whose predicate is resolved at a Nullable type while the granule column is the plain storage type. This happens when the query wraps the indexed expression argument with toNullable() (e.g. t % toNullable(19) = 2), or when the column is read through a MaterializedView that declares it Nullable.

Description

MergeTreeIndexConditionSet rebuilds the WHERE predicate onto the granule block, reusing the predicate's pre-resolved function nodes. Those functions may be resolved against a Nullable argument type (from a toNullable() in the query, or from an MV _CAST to a declared Nullable type), while the granule block carries the indexed expression at its plain storage type. ExpressionActions::execute then runs the function on the non-Nullable granule column, produces a non-Nullable result, and trips the result_type invariant:

Logical error: 'Unexpected return type from equals. Expected Nullable(UInt8). Got UInt8.
  FUNCTION equals(modulo(t, 19), 2) -> Nullable(UInt8); input modulo(t, 19) UInt8'

Fix: in MergeTreeIndexConditionSet::atomFromDAG, record each key column's granule (storage) type and, when it differs from the type the predicate expects, add an INPUT of the storage type plus a CAST back to the expected type. The pre-resolved functions then see the type they were resolved for, keeping the result_type invariant intact while the block fed into the actions stays the storage column unchanged. The skip index continues to prune granules as before.

Found by the server-side AST fuzzer (STID 1611-11ad/4523/447a/483a, 3262 family) on 01786_explain_merge_tree; also reported as issue #89802 (MV variant). Reproduces deterministically on a debug build:

SET enable_analyzer = 1;
CREATE TABLE t (t UInt32, INDEX t_set t % 19 TYPE set(4) GRANULARITY 2)
  ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 2, min_bytes_for_wide_part = 0;
INSERT INTO t SELECT number FROM numbers(20);
SELECT count() FROM t WHERE (t % toNullable(19)) = 2;  -- LOGICAL_ERROR before this fix

…anule is not

MergeTreeIndexConditionSet reused the predicate's pre-resolved function nodes
on the granule block. When the predicate is resolved at a Nullable type (query
uses toNullable(), or an MV declares the column Nullable) while the granule
column is the plain storage type, ExpressionActions::execute produced a
non-Nullable result and tripped the function result_type invariant:
'Unexpected return type from equals. Expected Nullable(UInt8). Got UInt8'.

Fix: in atomFromDAG, add an INPUT of the granule storage type and a CAST back
to the type the predicate expects when the two differ, so the pre-resolved
functions see their resolved types while the granule block stays unchanged.

Closes ClickHouse#89802.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET enable_analyzer=1; CREATE TABLE t (t UInt32, INDEX t_set t%19 TYPE set(4) GRANULARITY 2) ENGINE=MergeTree ORDER BY tuple() SETTINGS index_granularity=2, min_bytes_for_wide_part=0; INSERT INTO t SELECT number FROM numbers(20); SELECT count() FROM t WHERE (t % toNullable(19)) = 2; aborts (exit 134) every time on a debug build.
b Root cause explained? MergeTreeIndexConditionSet::atomFromDAG rebuilds the predicate onto the granule block reusing the pre-resolved function nodes. t % toNullable(19) makes the query-side modulo/equals resolve to Nullable(UInt8), but the set granule column carries t % 19 at plain UInt8. ExpressionActions::execute runs equals on the non-Nullable granule column, produces UInt8, and the saved result_type (Nullable(UInt8)) fails the invariant check → Unexpected return type from equals. Expected Nullable(UInt8). Got UInt8.
c Fix matches root cause? Yes. In atomFromDAG we record each key column's granule (storage) type; when it differs from the type the predicate expects, we add an INPUT of the storage type and CAST it back to node.result_type, so the pre-resolved functions see their resolved types while the block stays the storage column. Directly targets the type divergence, not a symptom.
d Test intent preserved / new tests added? New test 04538_set_index_nullable_return_type added, covering both triggers (query-side toNullable on a set-index expr; MV-declared Nullable over non-Nullable storage) and asserting the set index still prunes (Granules: 0/...). No existing test weakened.
e Both directions demonstrated? Yes. Without fix: exit 134 (SIGABRT, LOGICAL_ERROR). With fix (rebuilt, Build ID changed): exit 0, correct results, index still prunes 0/3 granules for the no-match predicate.
f Fix is general across code paths? The fix is in the single shared atomFromDAG used by all set skip-index atom construction (equals, IN, AND/OR/NOT all route through it), so it covers every predicate shape, not just the reported equals. Both the query-side and MV Nullable triggers of this invariant class are covered.
g Fix generalizes across inputs (params/datatypes/wrappers)? The storage-type-vs-predicate-type reconciliation is type-agnostic: it fires whenever storage_type != node.result_type for any key column, covering Nullable, wider-int (UInt8→Nullable(Int32)), and the MV _CAST case. Test exercises UInt32 storage with query-side Nullable and Int storage with MV Nullable(Int).
h Backward compatible? (maintainer-approved exception only) N/A — no setting default, on-disk/wire format, or validation change. Pure query-planning correctness fix; queries that previously crashed now return correct results.
i Invariants and contracts preserved? Yes. The ActionsDAG function result_type invariant is exactly what is restored. The granule block fed to ExpressionActions is unchanged (storage column at storage type); we only insert an INPUT+CAST so the pre-resolved functions receive the type they were resolved for. Skip-index pruning semantics preserved (verified via EXPLAIN indexes=1).

Session id: cron:clickhouse-worker-slot-3:20260714-070000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @shankar-iyer — could you review? Fixes a LOGICAL_ERROR in MergeTreeIndexConditionSet::atomFromDAG: when a set-index predicate is resolved at a Nullable type (query-side toNullable(), or an MV declaring the column Nullable) but the granule column is the plain storage type, the reused pre-resolved function trips the result_type invariant. Fix adds an INPUT of the storage type + CAST back to the expected type; the index still prunes.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5c4b643]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Config Workflow ERROR
Dockers Build (amd) DROPPED
Dockers Build (arm) DROPPED
Dockers Build (multiplatform manifest) DROPPED
Style check DROPPED
Code Review DROPPED
Docs check DROPPED
Docs check (Mintlify) DROPPED
Fast test DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 14, 2026
…pe predicates correct

A mixed predicate reusing the same set-index expression at different types,
e.g. WHERE (t % 19) = 1 OR (t % toNullable(19)) = 2, canonicalizes both
branches to the same column name modulo(t, 19). The name-only key_column_inputs
cache returned the first branch's adapted node for the second, so the plain and
Nullable uses shared one node and the wrong-typed branch again hit
"Unexpected return type from equals. Expected Nullable(UInt8). Got UInt8".

Cache the storage-typed INPUT once per column and memoize the adapted node
(raw INPUT or its CAST) by (column name, expected type). Regression covers both
AND/OR orders of mixed plain and Nullable use of one set-index expression.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in 9e3d7b2. The name-only key_column_inputs cache is replaced: the storage-typed INPUT is cached once per column and shared as the cast source, and the adapted node (raw INPUT or its CAST) is now memoized by (column name, expected type). So WHERE (t % 19) = 1 OR (t % toNullable(19)) = 2 gets a distinct correctly-typed node per branch instead of collapsing onto one.

Confirmed the exact bug on the pre-fix build: the mixed predicate reproduces Unexpected return type from equals. Expected Nullable(UInt8). Got UInt8, and passes after the fix. Added a regression (04538) covering both AND/OR orders of mixed plain and Nullable use of the same set-index expression.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 9e3d7b2

Both failures below are the chronic trunk "Unexpected return type" AST-fuzzer family (STID 1611-*), not caused by this PR. This PR only touches src/Storages/MergeTree/MergeTreeIndexSet.{cpp,h} (set skip index (name,type) memoization) + its regression test 04538; the failing fuzzed queries are unrelated arithmetic/function return-type asserts that recur across many unrelated PRs and master. Our own test 04538 passed.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Unexpected return type ... Action: (STID 1611-447a) chronic trunk fuzzer LOGICAL_ERROR (4 unrelated PRs/30d) a fix task (investigating at full effort; fixing-PR link to follow here)
AST fuzzer (amd_debug, targeted) / Unexpected return type ... Action: (STID 1611-4523) chronic trunk fuzzer LOGICAL_ERROR (5 PRs + 1 master/30d) a fix task (investigating at full effort; fixing-PR link to follow here)
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260714-133000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 37/38 (97.37%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 112e5e8

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit the per-table concurrency throttle the test asserts is keyed on query id, and secondary parallel-replicas reads are sent without one, so the holder query competes against itself (3/3 reruns, deterministic) #112385 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-120000

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

Two AST-fuzzer aborts today reach assert_cast<const ColumnVariant &> at src/Functions/FunctionVariantAdaptor.cpp:96 through the set-index granule path, and I believe this PR already fixes them. Recording the evidence here so the connection is not lost, since the symptom text differs from this PR's.

The two rows (STID 3430-61a7 on AST fuzzer (arm_asan_ubsan), 3430-5ebe on AST fuzzer (amd_debug, targeted)) are ColumnNullable -> ColumnVariant and ColumnString -> ColumnVariant. Their stacks, read from the job logs rather than the truncated CI-database context, are:

FunctionVariantAdaptor.cpp:96  assert_cast<const ColumnVariant &>
  <- ExpressionActions.cpp:693/837/1003
  <- MergeTreeIndexSet.cpp:435 mayBeTrueOnGranule      (61a7)
  <- MergeTreeIndexSet.cpp:485 getPossibleGranules     (5ebe)
  <- MergeTreeDataSelectExecutor.cpp filterMarksUsingIndex

Same broken invariant this PR repairs, arriving with a Variant instead of a Nullable:

  • atomFromDAG matched key columns by name only and re-added the input with the query-side type, MergeTreeIndexSet.cpp:673 addInput(column_name, node.result_type), while the granule block is materialized at the storage type from index_sample_block.
  • ExpressionActions::execute binds inputs by name with no type check (ExpressionActions.cpp:816 looks the block column up by name and :823 binds it; the INPUT action at :789 only moves the column across) and validates just the function result type at :694.

The Variant typing here comes from Merge: getLeastSupertypeOrVariant at StorageMerge.cpp:251 unifies differing child column types, and both failing queries read merge('.*'). On master, DESCRIBE merge(currentDatabase(), '^t_') over t_str(v String) plus t_int(v Int64) gives v Variant(Int64, String), so the predicate types v as Variant while each child's granule holds String or Int64.

Measured on a debug build at 31081d9f0501400, with a 40-row fixture and a set(100) index on v:

  • same-type merge() (both children String), WHERE v = '7' gives Skip / Name: idx_v / Condition: (v in ['7','7']) / Granules: 1/10;
  • Variant-unified merge(), same query, gives Skip / Name: idx_v / Condition: true / Granules: 1/10.

So the set index is genuinely consulted on the Variant path, and the condition degenerating to true is the observable signature of the Variant-typed input reaching it.

This PR's guard is !storage_type->equals(*expected_type), a plain type comparison with no Nullable-specific narrowing, so a String or Nullable(String) granule column under a Variant(Int64, String) input takes the same branch. I also checked the remedy is sound for that branch: CAST to a Variant yields a real ColumnVariant (CAST('7', 'Variant(Int64, String)') gives Variant(size = 1, UInt8, UInt64, Int64, String), likewise from Nullable(String) and from Int64, which are the two incoming kinds in these rows). After the cast the adaptor receives a ColumnVariant, so line 96 cannot fire on this path.

Worth noting for whoever lands this: #113244 fixes the same lines differently, returning UNKNOWN_FIELD on a mismatched INPUT and re-resolving the function against the granule types. That approach also removes these two aborts. I am not opening anything for the Variant route; whichever of the two lands covers it.

For the record, this route is distinct from the executeDryRunImpl one (STID 3430-6122), which is driven by EXPLAIN PIPELINE over set operations and is not touched by this PR.

@PedroTadim

Copy link
Copy Markdown
Member

Closing in favour of #113244

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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants