Skip to content

Do not throw on a comparison of an Enum with a non-member string literal - #118398

Closed
alexey-milovidov wants to merge 6 commits into
masterfrom
enum-non-member-literal-comparison-111545
Closed

alexey-milovidov wants to merge 6 commits into
masterfrom
enum-non-member-literal-comparison-111545

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

Comparing an Enum column with a string literal that is not a member of the enum threw
UNKNOWN_ELEMENT_OF_ENUM in three cases, even with the default validate_enum_literals_in_operators = 0,
which documents that such a literal must not throw:

  • for != on any column: the operator filter in FunctionComparison::executeWithConstString reads
    !equals && not_equals, so the tolerant path was taken for every operator except the one it was meant
    to cover, and != fell through to convertFieldToType, which throws;
  • for every comparison operator on a column that belongs to the sorting or partition key: KeyCondition
    converts the literal to the key type before the predicate is ever evaluated, so the same query over the
    same data answered or failed depending on the physical layout of the table;
  • for a column covered by a bloom_filter skip index: that index builds its own RPN, and
    MergeTreeIndexConditionBloomFilter::traverseTreeEquals converts the constant to the indexed type to
    hash it. bloom_filter indexes accept Enum columns, so e = '4', e != '4', has(a, '4'),
    indexOf(a, '4'), hasAny/hasAll, mapContainsValue and an ARRAY JOINed x = '4' threw there
    as well.

A literal that converts to no value of the compared type is false for =, <, >, <=, >= and true
for !=, as toUInt8(1) = '257' already is. Enum comparison now follows that rule for every operator, and
both key analysis and the bloom_filter condition builder decline the atom instead of converting it,
leaving the predicate to be evaluated. With validate_enum_literals_in_operators = 1 the comparison still
throws, now the same way whatever the physical layout is.

The map branches of the same bloom_filter condition builder - m['k'] = c and m['k'] IN (...) over an
INDEX ... mapKeys(m) or mapValues(m) - turned out never to convert the constant at all: they hashed the
Field as it arrived, and BloomFilterHash::hashWithField reads it as the indexed type. So the enum literal
threw Bad get: has String, requested Int64 (BAD_GET) there rather than UNKNOWN_ELEMENT_OF_ENUM, and it
threw for a literal naming a member too. Every type whose string literal the comparison itself leaves a
String hit the same wall, so Map(String, DateTime) and Map(String, UUID) threw alike, as did an Enum
map key in the arrayElement form, where the key literal is not deserialized with the key type the way a
map.key_<key> subcolumn's is. Both branches now convert the constant to the indexed type before hashing it
and decline the atom when it converts to no value of that type.

The map atom is also declined when its key is a string naming no member of the map's Enum key type.
m['missing'] throws UNKNOWN_ELEMENT_OF_ENUM there, but an index on mapValues(m) ignores the key, so it
could prune every granule by the value alone and turn that exception into an empty result.

Closes: #111545
Related: #72686

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 to CHANGELOG.md):

Comparing an Enum column with a string literal that is not a member of the enum no longer throws
UNKNOWN_ELEMENT_OF_ENUM with the default validate_enum_literals_in_operators = 0. Previously != threw
on any column, and every comparison operator threw when the column belonged to the sorting or partition key
or was covered by a bloom_filter skip index. Also fixed comparing a key or a value of a Map column
covered by a bloom_filter index on mapKeys or mapValues with a string literal, which threw BAD_GET
for an Enum, a DateTime or a UUID.

🤖 Generated with Claude Code


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

…teral

With the default `validate_enum_literals_in_operators = 0`, comparing an `Enum` column with a string
literal that is not a member of the enum threw `UNKNOWN_ELEMENT_OF_ENUM` in two cases, while the
setting documents that such a literal must not throw:

- for `!=` on any column: the operator filter in `FunctionComparison::executeWithConstString` read
  `!equals && not_equals`, so the tolerant path was taken for every operator *except* the one it was
  meant to cover, and `!=` fell through to `convertFieldToType`, which throws;
- for every comparison operator on a column that belongs to the sorting or partition key:
  `KeyCondition` converts the literal to the key type before the predicate is ever evaluated, so the
  same query over the same data answered or failed depending on the physical layout of the table.

A literal that converts to no value of the compared type is `false` for `=`, `<`, `>`, `<=`, `>=` and
`true` for `!=`, as `toUInt8(1) = '257'` already is. Enum comparison now follows that rule for every
operator, and key analysis declines the atom instead of converting it, leaving the predicate to be
evaluated. With `validate_enum_literals_in_operators = 1` the comparison still throws, now for a key
and a non-key column alike.

Closes: #111545

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dcda1cc]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Cannot check whether the mutation submitted before the upgrade was finished (see mutation_across_upgrade_error.txt) FAIL cidb
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb
Storage memory check FAIL
03_add_secondary_indexes.sql FAIL cidb

AI Review

Summary

This PR extends the enum-non-member literal fix into KeyCondition and the bloom_filter condition builder, and it adds focused stateless coverage for the regressions found during review. One blocker remains: the direct comparison fast path still only recognizes bare Enum8 / Enum16, so wrapped enum columns still throw on non-member string comparisons with the default validate_enum_literals_in_operators = 0.

Findings

❌ Blockers

  • [src/Functions/FunctionsComparison.h:1219] The new is_string_not_in_enum fast path checks only a bare DataTypeEnum8 / DataTypeEnum16 on type_to_compare. For Nullable(Enum(...)) and LowCardinality(Enum(...)), both casts miss, execution falls through to convertFieldToType(string_value, *type_to_compare, ...), and convertFieldToType unwraps those wrappers and still throws UNKNOWN_ELEMENT_OF_ENUM. That leaves comparisons like e = '4' and e != '4' broken for wrapped enum columns even though the PR and changelog claim the comparison no longer throws. Suggested fix: run the membership check on removeLowCardinalityAndNullable(type_to_compare) (or teach stringConstantIsNotAnEnumMember to unwrap wrappers) and add a regression test for both wrapped forms.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit dcda1cc.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 81/89 (91.01%) · 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 6, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 6, 2026
@zlareb1

zlareb1 commented Sep 6, 2026

Copy link
Copy Markdown
Member

TL;DR: the KeyCondition decline covers the primary key, the partition key, and the minmax and set skip indexes (their conditions are built on KeyCondition — verified by stack), but the bloom_filter skip index converts the literal in its own RPN builder, which still throws. With INDEX ... TYPE bloom_filter on the enum column, e = '4' and e != '4' keep throwing UNKNOWN_ELEMENT_OF_ENUM at pure defaults after this PR, so the outcome still depends on physical layout, and the changelog claim for != ("threw on any column") stays false for a bloom-indexed column.

1. The remaining throw

CREATE TABLE t_bf (e Enum8('a' = 1, 'b' = 2), INDEX ibf e TYPE bloom_filter GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t_bf VALUES ('a'), ('b');
SELECT count() FROM t_bf WHERE e = '4';
-- Code: 691. DB::Exception: Unknown element '4' for enum ... (UNKNOWN_ELEMENT_OF_ENUM)
-- returns 0 without the index

Measured on 26.9.1.1; the diff does not touch this path. The stack is convertFieldToTypeImpl ← MergeTreeIndexConditionBloomFilter::traverseTreeEquals (the convertFieldToType(value_field, *actual_type, value_type.get()) right after out.function is set to FUNCTION_EQUALS/FUNCTION_NOT_EQUALS in MergeTreeIndexBloomFilter.cpp) ← ReadFromMergeTree::buildIndexes. BloomFilter::getPrimitiveType unwraps only Array, Nullable and LowCardinality, so the target type stays Enum8/Enum16 and the String literal conversion throws for a non-member. The same guard (or a tryConvertFieldToType with a decline on Null) is needed there, for equals and notEquals alike.

2. Verified the rest of the index coverage both ways

The set index's pre-PR throw routes through KeyCondition::extractAtomFromTree (stack: MergeTreeIndexSet.cpp createIndexCondition → KeyCondition), and the minmax index's throw does too, so both are fixed by the new decline. The bloom IN/NOT IN path uses the prepared set and already answers correctly (probed 1/1), so within this PR's scope only the bloom equals/notEquals atoms remain.

3. A bonus this PR quietly delivers, probed correct

e LIKE 'a%' over an Enum key throws today for the same reason (a pattern string is converted to the key type before the like atom is built) and the decline fixes it, since a pattern is almost never a member. The adversarial case — a member name that itself contains a like-metacharacter, Enum8('a%' = 1, 'ab' = 2) with ORDER BY e, index_granularity = 1 — returns the correct 2 rows both with and without the key, so letting a member-name pattern through to convertFieldToType does not mis-prune.

For reference, the earlier fix attempt #114035 for the same issue also patches the bloom_filter sites.

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

alexey-milovidov and others added 2 commits September 11, 2026 06:25
`KeyCondition` now declines an atom whose string constant names no member of the enum, but the
`bloom_filter` skip index builds its own RPN: `MergeTreeIndexConditionBloomFilter::traverseTreeEquals`
converts the constant to the indexed type to hash it, and `bloom_filter` indexes accept `Enum` columns.
So with `INDEX ... TYPE bloom_filter` on an enum column (or on an `Array(Enum)`, or on
`mapValues` of a map with an enum value type), `e = '4'`, `e != '4'`, `has(a, '4')`, `indexOf(a, '4')`,
`hasAny`/`hasAll`, `mapContainsValue` and an `ARRAY JOIN`ed `x = '4'` still threw
`UNKNOWN_ELEMENT_OF_ENUM` with the default `validate_enum_literals_in_operators = 0`, while the same
query over the same data answered without the index - the outcome depended on the physical layout again.

Apply the same rule there: decline the atom and let the predicate be evaluated. The check moved from
`KeyCondition.cpp` to `stringConstantIsNotAnEnumMember` next to `convertFieldToType`, which is what it
guards, and is applied at every site of the bloom-filter condition builder that converts a comparison
constant, including the per-element conversion for a constant array.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`m['k'] = c` and `m['k'] IN (...)` over an `INDEX ... mapKeys(m)` or `mapValues(m)` never converted the
comparison constant to the indexed type: they hashed the `Field` as it arrived, and
`BloomFilterHash::hashWithField` reads it as the indexed type. So an `Enum`, a `DateTime` or a `UUID`
compared with a string literal - which the comparison itself leaves a `String`, see
`FunctionComparison::executeWithConstString` - threw `Bad get: has String, requested Int64` (`BAD_GET`)
rather than answering, and threw it for a literal naming a *member* too, not only for the non-member
literal the rest of this branch is about. The same holds for an `Enum` map key in the `arrayElement` form,
where the key literal is not deserialized with the key type as it is for a `map.key_<key>` subcolumn.

Both branches now go through one `hashMapConstant`, which declines a string literal naming no member of an
`Enum`, converts the constant to the indexed type, declines when it converts to no value of that type, and
only then hashes it. Declining is not what makes the answers right: a constant that does convert is still
hashed and the index still prunes, which `05183_bloom_filter_map_constant_conversion` asserts with
`EXPLAIN indexes = 1`.

`05101_enum_non_member_string_literal` gains the enum map cases in both
`optimize_functions_to_subcolumns` forms; the new test covers the `DateTime`, `UUID` and `Enum`-key cases
against an unindexed control table.
alexey-milovidov and others added 2 commits September 23, 2026 11:06
…`Enum` member

`m['k']` throws `UNKNOWN_ELEMENT_OF_ENUM` when `k` names no member of the `Enum` key
type of `m`. An index on `mapValues(m)` ignores the key, so for `m['missing'] = 'x'`
or `m['missing'] IN (...)` it could prune every granule by the value alone, and the
query returned `0` instead of throwing. Decline the atom in
`tryResolveMapInfoFromNode`, which covers both the `equals` and the `IN` branches.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

Field string_value = left_const ? left_const->getField() : right_const->getField();

/// A string literal that is not a member of the enum converts to no value of the compared type, so it

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.

This still misses wrapped enum columns. type_to_compare here is the original argument type, so for Nullable(Enum8(...)) or LowCardinality(Enum8(...)) both typeid_cast<const DataTypeEnum8 *>(type_to_compare.get()) and typeid_cast<const DataTypeEnum16 *>(type_to_compare.get()) return nullptr. The new fast path is then skipped, and the next convertFieldToType(string_value, *type_to_compare, ...) unwraps those wrappers and still throws UNKNOWN_ELEMENT_OF_ENUM, so comparisons like e = '4' and e != '4' keep failing at pure defaults on wrapped enum columns even though the PR/changelog says these comparisons no longer throw. Please run the check on removeLowCardinalityAndNullable(type_to_compare) (or have stringConstantIsNotAnEnumMember unwrap wrappers) and add a regression test for Nullable(Enum) / LowCardinality(Enum).

@rschu1ze

Copy link
Copy Markdown
Member

Will be fixed in #122672

@rschu1ze rschu1ze closed this Sep 28, 2026
@clickhouse-gh clickhouse-gh Bot added comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

3 participants