Skip to content

Fix set index on an expression with a Nullable operand - #113244

Merged
alexey-milovidov merged 19 commits into
masterfrom
fix-set-index-nullable-operand-type
Aug 18, 2026
Merged

alexey-milovidov merged 19 commits into
masterfrom
fix-set-index-nullable-operand-type

Conversation

@george-larionov

@george-larionov george-larionov commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

A SELECT filtered on an expression that matches a set skip index raises LOGICAL_ERROR:

CREATE TABLE events (id UInt32, INDEX b_set intDiv(id, 1000) TYPE set(100) GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO events SELECT number FROM numbers(5000);

SELECT count() FROM events WHERE intDiv(id, (SELECT 1000)) = 3;
-- Code: 49. Unexpected return type from equals. Expected Nullable(UInt8). Got UInt8.

SELECT 1000 is Nullable(UInt16), while the underlying column type of the index is plain UInt32, so when MergeTreeIndexConditionSet rewrites the predicate it loses the Nullable type and just saves that it is a UInt. However the equals function still expects a Nullable, and this mismatch throws an error in ExpressionActions.cpp:executeAction.

============================================

No Nullable appears anywhere in the schema or the query. A scalar subquery is typed Nullable because it may return no rows, and that is enough. In practice this shows up when the divisor or bucket size comes from a lookup or settings table instead of a literal; the typing is identical. Explicit wrappers reach the same failure: nullIf(1000, 0), toNullable(1000).

MergeTreeIndexConditionSet matched a query subexpression to an index key column by name only. Names are computed from constant-folded arguments and never include types, so intDiv(id, (SELECT 1000)) renders exactly like the index expression intDiv(id, 1000) while carrying Nullable(UInt32). The whole subtree was then replaced by the granule column while the enclosing equals was re-added with its already-resolved IFunctionBase, keeping the return type it was resolved with. ExpressionActions::execute binds inputs by name without checking types, so the granule supplied a non-Nullable column and the declared return type no longer matched what execution produced.

atomFromDAG now binds the key column input to the type the granule block holds and restores the query-side type on top of it with toNullable, so the enclosing atom keeps the IFunctionBase it was resolved with. The atom function is not re-resolved from FunctionFactory, so there is no resolution failure to catch. A chassert pins the postcondition that the node handed back carries the type the query side expects.

toNullable changes the type and not the data: the granule column's null map is all zeros, so equals produces no NULL, the ifNull that traverseDAG adds for a Nullable atom substitutes nothing, and the mask is bit-for-bit what the non-Nullable atom produces. Pruning is therefore unchanged rather than merely correct — EXPLAIN indexes = 1 reports the same 5/50 granules for t % nullIf(19, 0) = 16, t % toNullable(19) = 16, t % (SELECT 19) = 16 as for the plain t % 19 = 16.

Two cases fall back to UNKNOWN_FIELD, which leaves the granule unpruned and sends the query through the regular filter path. A key column that is already an INPUT of the filter DAG, which cannot be re-typed, because a second input under the same name would be left unbound where ExpressionActions::execute maps each name to one block column. And a type difference that is not a Nullable the query side added: toNullable over the granule type has to reproduce the query-side type exactly, since dropping a Nullable the granule holds would substitute values for its NULLs.

The regression test covers both granule filtering paths, since secondary_indices_enable_bulk_filtering selects between getPossibleGranules and mayBeTrueOnGranule, and each reaches the same actions independently. An index whose expression is itself Nullable is unaffected in either direction, because the types agree and nothing is re-typed; such an index prunes conservatively both before and after this change, because the granule genuinely stores NULLs and each maps to UNKNOWN_FIELD.

Reproduces on the official release 26.8.1.727. In builds with assertions enabled it aborts the server, which is how it surfaced in CI — 14 occurrences in 90 days across unrelated pull requests and every build configuration, through tests/queries/0_stateless/01786_explain_merge_tree.sh once the AST fuzzer wraps the modulus in a Nullable expression.

Closes: #113233
Closes: #113234
Related: #113233
Related: #89802
Related: #111830

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 LOGICAL_ERROR when reading a table with a set skip index defined on an expression and the query repeats that expression with a Nullable operand, for example WHERE intDiv(id, (SELECT 1000)) = 3 over INDEX b_set intDiv(id, 1000) TYPE set(100). A scalar subquery is enough to trigger it, since it is typed Nullable.


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

Version info

  • Merged into: 26.8.1.1673 (included in 26.8 and later)
  • Backported to: 26.7.7.50, 26.6.5.75, 26.3.33.13

`MergeTreeIndexConditionSet` matched a query subexpression to an index key column
by name only. A `Nullable` operand folding to the same name made it substitute the
granule column and drop the operand, while the reused function still declared a
`Nullable` return type, raising `LOGICAL_ERROR`. Require the types to match and
fall back to `UNKNOWN_FIELD` otherwise.

Closes: #113234
Related: #113233

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

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4e72aa8]

Summary: ✅


AI Review

Summary

This PR teaches MergeTreeIndexConditionSet to preserve the query-side Nullable type when a set skip index key matches by name but the granule stores the non-Nullable version, and it adds focused stateless coverage for both bulk and non-bulk pruning paths. I re-checked the current code against the existing review threads and did not find any remaining correctness, pruning, or metadata issues in the live diff.

Final Verdict

✅ No blocking issues found in the current diff.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 28/31 (90.32%) · 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 4, 2026
george-larionov and others added 3 commits August 5, 2026 01:54
Pin `use_skip_indexes = 1` and check `EXPLAIN indexes = 1` so the test proves it
exercised the skip index path instead of inferring it from the row counts.

Co-Authored-By: Claude Opus 5 <[email protected]>
A scalar subquery is typed `Nullable` because it may return no rows, so
parameterising the indexed expression from a lookup table hits the same collision
with no `Nullable` in the schema or the query text. Also shorten the comment in
`atomFromDAG`.

Co-Authored-By: Claude Opus 5 <[email protected]>
A bare `(SELECT 19)` is typed `Nullable` for the same reason and reaches the same
collision, so the table and its two setup statements were dead weight.

Co-Authored-By: Claude Opus 5 <[email protected]>
george-larionov and others added 2 commits August 5, 2026 07:35
Re-resolve the atom's function against the granule-side argument types and bind the
input to the granule column's own type, instead of reusing the query-side
`IFunctionBase` and its stale return type. Functions that cannot be re-resolved
still fall back to `UNKNOWN_FIELD`, as does an existing INPUT, which cannot be
re-typed.

Co-Authored-By: Claude Opus 5 <[email protected]>
Without `secondary_indices_enable_bulk_filtering` the condition runs through
`mayBeTrueOnGranule`, which evaluates the hyperrectangle check before the same
actions. That path fails on its own without the fix.

Co-Authored-By: Claude Opus 5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Aug 13, 2026
george-larionov and others added 2 commits August 13, 2026 22:36
Wrapping the granule input in `toNullable` keeps the atom's already-resolved
`IFunctionBase` valid, so `atomFromDAG` no longer re-resolves the function from
`FunctionFactory` and no longer catches the exception that can raise. Granule
counts are unchanged: the `Nullable` variants prune 5/50, same as the plain query.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment-only: the generated code is unchanged.

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

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4e72aa818 with master 08fb6b41e (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
Binary Master PR Δ
programs/clickhouse-stripped 701.29 MiB 698.27 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

The `Nullable` shapes asserted only `count()`, so an atom degrading to
`UNKNOWN_FIELD` would keep the test green while the index stopped pruning. Assert
`Granules: 5/50` for the plain and `Nullable` shapes in both bulk filtering
regimes, and pin the settings that move pruning out of index analysis.

Co-Authored-By: Claude Opus 5 <[email protected]>
george-larionov and others added 2 commits August 14, 2026 19:07
It was the one `Nullable` shape asserting only `count()`. `nullIf(19, 0)` folds
to a constant before index analysis, so it renders as `modulo(t, 19)`, matches
the key column and prunes 5/50 like the plain expression.

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

Copy link
Copy Markdown
Member

🕵 The previous Stress test (amd_msan) failure in Parquet::Reader::decodePrimitiveColumn (STID 2508-3e97) is unrelated to this PR. The same defect is tracked at #113841 and has a fix in progress at #113956.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 18, 2026
Merged via the queue into master with commit 3e5c1bc Aug 18, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-set-index-nullable-operand-type branch August 18, 2026 23:56
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 2026
@clickgapai

clickgapai commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor
Reproducer
CREATE TABLE t_113234 (t UInt32, INDEX t_set t % 19 TYPE set(4) GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 2;
INSERT INTO t_113234 SELECT number FROM numbers(100);

SELECT count() FROM t_113234 WHERE t % toNullable(19) = 16;
-- expected 5; on 25.3..26.7:
-- Code: 49. DB::Exception: Unexpected return type from equals. Expected Nullable(UInt8). Got UInt8.
--   ... while executing 'FUNCTION equals(modulo(t, 19) :: 0, 16 :: 1) -> equals(modulo(t, 19), 16) Nullable(UInt8)' (LOGICAL_ERROR)
-- Same failure for t % nullIf(19, 0) = 16 and t % (SELECT toNullable(19)) = 16.

Results:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3, 25.8
  • Does not reproduce on: master
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5, 26.3, 25.8.

CC component owner: @shankar-iyer @rschu1ze

Analysis metadata

comp-skip-index · Severity P2 · Finding phase_d_pr113244

  • Verified against master build 1e9f2596dac0 (aarch64)
Introducing change: not identified
  • Secondary components: comp-testing

@PedroTadim

Copy link
Copy Markdown
Member

Backporting this PR to fix stress test in backport branches

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 8, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 8, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 8, 2026
Backport #113244 to 26.6: Fix set index on an expression with a Nullable operand
PedroTadim added a commit that referenced this pull request Sep 8, 2026
Backport #113244 to 26.3: Fix set index on an expression with a Nullable operand
PedroTadim added a commit that referenced this pull request Sep 8, 2026
Backport #113244 to 26.7: Fix set index on an expression with a Nullable operand
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
STOR: set index on an expression that the query repeats with a Nullable operand (e.g. a scalar subquery) -> exc LOGICAL_ERROR.
Effect in the production build a394e92: wrong/failing (the upstream test fails on it and passes on official 26.8.8.8; evidence/fix_ci_20260925/upstream_repro/residual/113244.PROD263.txt).
Upstream patch unchanged, with its test(s): 04700_set_index_nullable_operand_in_expression.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.3-must-backport

Projects

None yet

7 participants