Skip to content

Do not throw when comparing an Enum column with a non-member string literal - #114035

Closed
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:fix-enum-non-member-literal-key-analysis
Closed

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:fix-enum-non-member-literal-key-analysis

Conversation

@groeneai

@groeneai groeneai commented Aug 9, 2026 •

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

Fixes UNKNOWN_ELEMENT_OF_ENUM being thrown when an Enum column is compared with a string literal that is not one of its members, even though validate_enum_literals_in_operators is disabled by default. Previously the query was rejected if the column was in the primary key or partition key, or merely carried a minmax, set or bloom_filter index, and != was rejected for any Enum column. Closes #111545.

Description

Closes: #111545

validate_enum_literals_in_operators is off by default and documents that non-member enum literals are then not validated, yet comparing an Enum column with one threw, and whether it threw depended on physical layout. Two independent causes:

  1. Index analysis. KeyCondition::extractAtomFromTree converts the literal with the throwing convertFieldToType, leaving the isNull() handling right below it unreachable. Since minmax and set build a KeyCondition over the index expression, that one line served the primary key, the partition key and both indexes. bloom_filter repeated the defect at four of its own sites, as did the JSON-subcolumn helper shared by bloom_filter and tokenbf_v1. The conversions now catch only UNKNOWN_ELEMENT_OF_ENUM, so a string naming no member declines the atom (full scan, never a wrong answer) while every other conversion error, including an unparseable DateTime64 literal, propagates exactly as on master.

  2. An inverted guard. In FunctionsComparison.h, !equals && not_equals selects notEquals alone, yet the value it guards, IsOperation<Op>::not_equals, was written to serve notEquals, so the tolerant branch could only ever return 0. Deleting the guard is the fix: any rewrite that keeps a condition there breaks the four ordered operators, for which both traits are false.

Two corrections to the report, both re-measured. e < '4' does not throw on a non-key column (the ordered operators all return 0), so there only != was broken; and the column need not be in a key, since a minmax, set or bloom_filter index suffices. e <=> '4' and isDistinctFrom(e, '4') were affected too.

No query that previously succeeded changes its answer, and declining loses no pruning: LIKE over an Enum key never pruned before, since the converted field is an Int8 that the like atom handler rejects. The tests assert that each index is still used for representable literals, and that the setting still rejects every operator when enabled.

Validation

Every carrier measured on a debug build, before and after, each fixture carrying a positive control:

Carrier Before After Control
primary key ORDER BY e 691 0 = 'a' -> 1
partition key, LIKE '%Beta%' 691 500 use_partition_pruning = 0 -> 500
minmax index, no key 691 0 use_skip_indexes = 0 -> 0
set(0) index, no key 691 0 use_skip_indexes = 0 -> 0
bloom_filter index, no key 691 0 use_skip_indexes = 0 -> 0
bloom_filter over Array(Enum), has / hasAny / hasAll 691 0 has(a, 'a') -> 1
bloom_filter over Map(Enum, ...) keys, mapContains 691 0 mapContains(m, 'a') -> 1
JSONAllPaths bloom_filter / tokenbf_v1 691 0 = 'y' -> 1, index used
!= on any table 691 row count NOT (e = 'zzz') agrees
<=>, isDistinctFrom 691 0 / row count member-literal arms
< <= > >= on a non-key column 0 0 unchanged
IN ('4', 'a') 1 1 unchanged (#72686)

Each of the four hunks was reverted independently: every one reddens its own carrier and only its own carrier. The tests assert index usability through force_data_skipping_indices rather than row counts alone, so neither an over-broad decline nor a missing one can pass silently; four mutations were run and each reddens a new assertion. Nullable(Enum8), Nullable(Enum16) and Enum16 keys covered, including a real NULL row (NULL != '4' stays NULL; NULL <=> '4' is 0). LowCardinality(Enum) is not covered because DataTypeEnum does not override canBeInsideLowCardinality(), so the type cannot be constructed. 50 randomized runs of both new tests passed 100/100; 01310_enum_comparison, 03278_enum_in_unknown_value, 04049_statistics_enum_invalid_value and 04539_enum_string_search_dictionary stay green.


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

groeneai and others added 2 commits August 9, 2026 10:23
…iteral

At the default validate_enum_literals_in_operators = 0 the setting documents
that non-member enum literals are not validated, yet comparing an Enum column
with one raised UNKNOWN_ELEMENT_OF_ENUM, and whether it did depended on the
physical layout of the table. Two independent defects caused it.

Index analysis converted the literal to the key type with the throwing
convertFieldToType in KeyCondition::extractAtomFromTree, which made the
isNull() handling directly below it unreachable even though that handling
exists for exactly this case. Because minmax and set build their own
KeyCondition over the index expression, that one line served the primary key,
the partition key and both of those indexes; bloom_filter does not use
KeyCondition and repeated the same pattern at four of its own sites, as did
the JSON subcolumn helper shared by the bloom_filter and tokenbf_v1 families.
Each conversion is now wrapped in a catch scoped by isParseError, following
the existing precedent in ConditionSelectivityEstimator, so a literal with no
representation in the target type declines the atom (an un-prunable full scan,
never a wrong answer) while fatal errors such as MEMORY_LIMIT_EXCEEDED,
cancellation and logical errors keep propagating. In the JSON helper an
explicit isNull() check was also needed: comparing a null Field against
getDefault() is false, so without it a failed conversion would have reported
"safe to skip this granule" off a comparison that never happened.

The second defect was an inverted guard on the notEquals tolerance in
FunctionsComparison.h. Its condition, !equals && not_equals, is true for
notEquals alone, while the value the tolerant branch returns,
IsOperation<Op>::not_equals, was written to serve notEquals. The branch could
therefore only ever return 0 and its true case was dead. Deleting the guard is
the correct fix: any rewrite that keeps a condition there sends the four
ordered operators, for which both traits are false, into the throwing
conversion and turns operators that work today into throwers.

Declining an atom loses no pruning that exists today. LIKE over an Enum key
never pruned before this change, because the converted field is an Int8 and
the like atom handler requires a String, so the only behaviour that changes on
these paths is an exception becoming an answer. ALTER ... PARTITION literal
resolution is deliberately untouched, so a bad partition literal keeps being
rejected, and with the setting enabled every operator still throws.

Two details of the report are corrected by measurement: the ordered operators
do not throw on a non-key column, so on that path only != was affected, and
the column does not need to be in a key at all, since attaching a minmax, set
or bloom_filter index to an Enum column in no key is sufficient. e <=> '4' and
isDistinctFrom(e, '4') share both code paths and were affected as well.

Closes: ClickHouse#111545
… tests

The result counts alone could not tell "declines this invalid literal" from
"declines every Enum predicate": each assertion was paired with a
use_skip_indexes = 0 twin returning the same value, so an unconditional decline
at any of the independently changed conversion sites would have left the
reference files byte-identical.

Assert index usability directly with force_data_skipping_indices, which raises
INDEX_NOT_USED once a skip index becomes alwaysUnknownOrTrue: a member literal
must still use each index, a non-member literal must decline it. Verified by
mutation: over-declining in either the bloom filter helper or KeyCondition now
reddens the key-analysis test, and either new fail-closed branch in the JSON
subcolumn helper reddens the JSON test.

Two behaviours were measured rather than assumed. set(N) decides usability
structurally, not from a KeyCondition atom, so it keeps using the index for a
non-member literal and the test asserts that instead. The JSON helper declines
the Enum's default value by a pre-existing rule, so the usable arm compares
against a non-default member.

Also cover a non-Enum key type: a literal outside the cast target's range
converts to a null Field without throwing, which is the shape the added null
check actually guards.

Add the missing tag lines (no-parallel-replicas on both, no-fasttest on the
JSON test, matching every in-tree JSONAllPaths index test), pin the plan
renderer for the EXPLAIN assertions, and drop the obsolete
allow_experimental_json_type setting.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two review rounds. Round 1 raised three test-liveness blockers, all AGREEd and fixed
(test-only; src/ byte-identical across the fix round, and the rebuild reproduced the same
Build ID). Round 2: 0 findings from either reviewer.

❌ Result-count-only skip-index oracle (AGREE, fixed). The skip-index sections asserted row
counts, each paired with a use_skip_indexes = 0 twin returning the same value, so "declines
this literal" was indistinguishable from "declines everything". Now asserted through
force_data_skipping_indices in both directions for every carrier. Proof the finding was real:
with the bloom-filter helper stubbed to return {}, the entire pre-existing count section stays
byte-identical to the reference and only the new assertion reddens.

❌ Same vacuity in the JSON test, plus unmeasured breadth (AGREE, fixed). The added
converted.isNull() check sits in a helper shared by bloom_filter and tokenbf_v1 for every
key type, not just Enum. The mutation that drops only that clause did not redden at first;
probing for a shape where convertFieldToType returns null without throwing found numeric
overflow, and CAST(j.a AS UInt8) = 999 now discriminates. The clause is load-bearing on a
non-Enum key type and was previously unasserted anywhere.

⚠️ Missing test tags (AGREE, fixed). Neither test carried -- Tags:.
automatic_parallel_replicas_mode is randomized to 2 with p=0.25, and index analysis is then
skipped on followers, which would make the new assertions non-deterministic. Both tests now
carry no-parallel-replicas; the JSON test also no-fasttest.

💡 Two notes recorded rather than papered over. set(N) decides usability structurally
(isUseless() is actions == nullptr), so it stays usable for a non-member literal and
evaluates the predicate over its stored set; the test asserts that, which is the stronger claim.
And the explain_query_plan_default = 'legacy' pin is defence-in-depth, not load-bearing: both
renderers print the asserted substring today.

One claim I raised and then withdrew on measurement: that the isParseError catch could swallow
a parse error some existing test asserts. It cannot. The two candidate tests do not reach the
changed line (one uses a temporary table, i.e. Memory, so no KeyCondition is built; the other
takes the should_keep_original_string_constant branch, and its exception comes from the runtime
matcher). A sweep of every stateless test that creates a MergeTree and asserts one of the 19
isParseError codes on a WHERE against a string literal found no affected case.

Session id: cron:clickhouse-review-slot-11:20260809-130900

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Answer
a Deterministic repro? Yes. CREATE TABLE k (e Enum8('a'=1,'b'=2)) ENGINE=MergeTree ORDER BY e; INSERT INTO k VALUES ('a'),('b'); SELECT count() FROM k WHERE e = '4'; gives Code: 691 on every run, no randomization needed. Seven further carriers reproduce the same way.
b Root cause explained? Yes. Two independent defects. (1) KeyCondition::extractAtomFromTree converts the literal with the throwing convertFieldToType, so the isNull() handling directly below it is unreachable; minmax and set reach it through their own KeyCondition, while bloom_filter and the JSON-subcolumn helper repeat the pattern at five more sites. (2) The notEquals tolerance guard in FunctionsComparison.h selects notEquals alone while the value it guards was written for notEquals, so the tolerant branch could only ever return 0.
c Fix matches root cause? Yes. The conversions get a catch scoped by isParseError, which is the in-tree contract for "this literal is not representable" (precedent: ConditionSelectivityEstimator.cpp). No widened bounds, no blanket catch (...), no no-random-* tag. The inverted guard is deleted rather than rewritten, because every conditional form breaks the four ordered operators.
d Test intent preserved / new tests added? Two new tests, no existing test weakened. Both assert index usability through force_data_skipping_indices, not only row counts, so an over-broad decline cannot pass unnoticed: a member literal must still use each of the five skip-index carriers and both JSON index types, a non-member literal must decline it. 04049_statistics_enum_invalid_value, which exists to assert enum-invalid-value tolerance, stays green along with 01310_enum_comparison, 03278_enum_in_unknown_value, 04539_enum_string_search_dictionary and both force_data_skipping_indices precedents.
e Demonstrated in both directions? Yes. Every carrier measured 691 before and its correct value after, on the same build tree with the Build ID checked. Each hunk was also reverted independently and each reddens only its own carrier. Four over-declining mutations were run as well (unconditional decline in the bloom filter helper, in KeyCondition, in the JSON helper, and dropping only the added null check): every one reddens a new assertion, so none of the branches is dead code. The last of those found a genuinely uncovered shape - a literal outside a non-Enum cast target's range converts to a null Field without throwing - which is now asserted.
f General across code paths? Yes. All seven reachable carriers were enumerated and fixed: primary key, partition key, minmax, set, bloom_filter (four sites incl. has/hasAny/hasAll over Array(Enum) and mapContains over Map(Enum, ...)) and the JSON-subcolumn helper shared by bloom_filter and tokenbf_v1. isJSONPathFilterSafe callers were re-grepped: both are covered. startsWith and empty over Enum reject the type earlier with Code: 43 and are out of scope.
g Generalizes across inputs? Yes. Nullable(Enum8), Nullable(Enum16) and Enum16 keys are covered, plus a real NULL row: NULL != '4' stays NULL rather than becoming 1, and NULL <=> '4' is 0. LowCardinality(Enum) is absent because DataTypeEnum does not override canBeInsideLowCardinality(), so the type cannot be constructed at all. IN with mixed member and non-member elements still returns the matching rows.
h Backward compatible? Yes. No default change, no new setting, no serialization change, so no SettingsChangesHistory.cpp entry is required. Queries that previously errored now answer; no query that previously succeeded changes its result. With the setting enabled the behaviour is unchanged.
i Invariants and contracts preserved? Yes. return false from extractAtomFromTree means FUNCTION_UNKNOWN, i.e. un-prunable, which is the function's own documented safe response; the adjacent "exact conversion" comment stays true because only the failure path changed. Each bloom_filter site already treated a null as "index unusable". In the JSON helper an explicit isNull() check was added, because converted == getDefault() is false for a null and would otherwise have reported "safe to skip" off a conversion that never happened. Fatal errors still propagate.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @shankar-iyer @Ergus, could you review this? At the default validate_enum_literals_in_operators = 0, index analysis converted a non-member Enum literal with a throwing conversion, so one line in KeyCondition rejected the query for the primary key, the partition key and the minmax/set indexes, with bloom_filter repeating it at four of its own sites; separately, an inverted trait guard in FunctionsComparison.h disabled the tolerance for != alone.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9c3a8f1]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, azure, sequential) FAIL
04648_distributed_plan_task_error_propagation FAIL cidb
04340_distributed_plan_status_reenqueue_fault FAIL cidb

AI Review

Summary

This PR fixes the main Enum/string-literal exception in KeyCondition, the bloom-filter helpers, and the != comparison path, and the new stateless tests do a good job covering the default validate_enum_literals_in_operators = 0 behavior. I still see one user-visible regression in the enabled-validation path, so I would not merge it as-is.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/KeyCondition.cpp:4411-4422, src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp:778-792, src/Storages/MergeTree/MergeTreeIndexJSONSubcolumnHelper.cpp:149-159] [dismissed by author -- https://github.com/Do not throw when comparing an Enum column with a non-member string literal #114035#discussion_r3864959001] These new UNKNOWN_ELEMENT_OF_ENUM catches are unconditional. When an invalid Enum comparison reaches key/skip-index analysis before FunctionComparison validates it, the catch turns the atom into FUNCTION_UNKNOWN; with force_primary_key, force_index_by_date, or force_data_skipping_indices, the planner can now throw INDEX_NOT_USED instead of the promised UNKNOWN_ELEMENT_OF_ENUM. The author's own e = (SELECT '4') counterexample is enough to show the regression. Suggested fix: consult validate_enum_literals_in_operators at each catch site and rethrow UNKNOWN_ELEMENT_OF_ENUM when validation is enabled.
Tests
  • ⚠️ Add one focused regression per forced-index family using a non-folded constant shape, for example SELECT count() FROM t_key WHERE e = (SELECT '4') SETTINGS validate_enum_literals_in_operators = 1, force_primary_key = 1. The current tests only use direct string literals, which are validated earlier and do not exercise these new catch blocks with the setting enabled.
Final Verdict

Changes requested: the default-path fix looks sound, but the enabled validate_enum_literals_in_operators contract still regresses on planner-only forced-index paths.

LLVM Coverage Report

Measured on commit 9c3a8f1.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 43/45 (95.56%) · 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 9, 2026
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 6505d0c

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
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 1/3) / 04862_enum_non_member_literal_key_analysis PR-caused: my own new test. Under old analyzer the two force_data_skipping_indices = 'i' queries succeed instead of raising INDEX_NOT_USED (277), 3/3 reruns. The index does get used on that path, so the serverError INDEX_NOT_USED assertion is wrong there fixed in this PR
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 1/3) / 04862_enum_non_member_literal_json_subcolumn_index PR-caused: same cause, my own new test (t_json_bf / t_json_tokenbf CAST-to-Enum subcolumn queries), 3/3 reruns fixed in this PR

Both tests pass on all 20 other flavours (including 50x flaky-check on 4 sanitizers and both
Bugfix validation arms); only the old analyzer flavour is red, so this is an
analyzer-dependent assertion in my tests, not a defect in the fix.

Session id: cron:our-pr-ci-monitor:20260809-220000

The old analyzer constant-folds a non-member Enum comparison to false before the
plan reaches ReadFromMergeTree, so the MergeTree read is dropped entirely and no
index analysis runs. force_data_skipping_indices therefore never raises
INDEX_NOT_USED, and EXPLAIN indexes = 1 emits no Indexes: block at all. That made
five assertions fail on the amd_llvm_coverage old-analyzer job while passing on 20
other flavours.

Only the five assertions whose predicate is a bare scalar comparison are pinned. The
has / hasAny / hasAll / mapContains arms and the CAST(j.a AS UInt8) = 999 arm are not
foldable and already raise INDEX_NOT_USED under both analyzers, so they stay
unpinned. A blanket no-old-analyzer tag was rejected: the notEquals, isDistinctFrom,
LIKE, NOT LIKE and partition-key LIKE shapes still reach the bug under the old
analyzer, and both tests were measured to still fail on a pristine-master binary
with the old analyzer, so tagging them out would have deleted live coverage.

The EXPLAIN pin goes on the outer query because changing enable_analyzer inside a
subquery raises INCORRECT_QUERY.

Verified: both tests pass under enable_analyzer 0 and 1 against the same reference
(25 randomized runs each, 100/100), still fail on the pristine-master binary under
both analyzers, and each pinned assertion was A/B'd fix-vs-base individually.
… setting is on

The enabled-setting section covered =, !=, <=> and isDistinctFrom but not <, <=, >
or >=, so a silent loss of validation for those four would have left it green. This
PR deletes a guard in the shared branch that all six operators reach, which is
exactly where such a regression would land.

Measured: all four throw UNKNOWN_ELEMENT_OF_ENUM at
validate_enum_literals_in_operators = 1 on both the fixed and the pristine-master
binary, and still return 0 at the default. A mutation that short-circuits the
ordered operators out of the setting-honouring branch reddens these four
assertions and nothing else.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the two test failures on Stateless tests (amd_llvm_coverage, old analyzer, ...) in 377c919. Test-only; the source diff is unchanged.

Cause: with the old analyzer a non-member Enum comparison is constant-folded to false before the plan reaches ReadFromMergeTree, so the table read is dropped and index analysis never runs. force_data_skipping_indices therefore cannot raise INDEX_NOT_USED, and EXPLAIN indexes = 1 emits no Indexes: block at all. Five assertions depended on that, which is why the two tests passed on 20 other flavours and failed only here.

I pinned enable_analyzer = 1 on exactly those five. The has / hasAny / hasAll / mapContains arms and the CAST(j.a AS UInt8) = 999 arm are not foldable and already raise INDEX_NOT_USED under both analyzers, so they stay unpinned. The EXPLAIN pin sits on the outer query because changing enable_analyzer inside a subquery raises INCORRECT_QUERY.

I did not tag the tests no-old-analyzer: the !=, isDistinctFrom, LIKE, NOT LIKE and partition-key LIKE shapes still reach the bug with the old analyzer, and both tests were measured to still fail against a pristine-master binary under it, so a blanket tag would have dropped live coverage.

Also added four assertions that <, <=, > and >= still reject a non-member literal when validate_enum_literals_in_operators = 1. That section previously covered only =, !=, <=> and isDistinctFrom, while this PR deletes a guard in the branch all six operators share.

Verified: both tests pass under enable_analyzer 0 and 1 against the same reference (25 randomized runs each, 100/100), and both still fail on a pristine-master binary under both analyzers.

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9c3a8f142 with master 55c256363 (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.

Object file sizes

11 object files changed (-532 B total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp.o 387.03 KiB 370.22 KiB -16.81 KiB (-4.34%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

24 translation units recompiled, 199 s compile time in total, 23 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 377c919

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
- no failed checks on this commit -

CI is fully finished on this head with zero failing checks. Config Workflow, Fast test and
Finish Workflow are all success; 157 of 175 check-runs concluded success and the 18
non-running ones each carry an explicit praktika reason (reused from cache, not affected by the changed files, not labeled with 'pr-performance', and similar); no job was dropped.
CIDB records 334569 test rows across 160 checks on this commit with 0 FAIL/ERROR.

This supersedes my ledger on the previous head 6505d0c47b65, which had 3 red rows; they are
gone on this head rather than merely un-run.

Session id: cron:our-pr-ci-monitor:20260810-063000

@rschu1ze

Copy link
Copy Markdown
Member

@nihalzp Like to check this one?

Master rewrote tryMatchJSONSubcolumnToIndex in
MergeTreeIndexJSONSubcolumnHelper.cpp and dropped the includes that
rewrite no longer needs. The only conflict was the include block: kept
master's removal of DataTypes/NestedUtils.h (unused after its rewrite)
and this branch's Formats/ParseError.h, which isJSONPathFilterSafe needs
for the isParseError-scoped catch. Both function bodies merge unchanged.

Verified the merged tree is byte-identical to this branch's diff
re-applied on the pinned master sha, submodule gitlinks included.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to resolve the conflict; the branch is mergeable again.

Master rewrote tryMatchJSONSubcolumnToIndex in MergeTreeIndexJSONSubcolumnHelper.cpp
(scan the index columns instead of the name's dot positions) and dropped the includes that
rewrite no longer needs. The only conflict was the include block, in a function this PR does
not touch: kept master's removal of DataTypes/NestedUtils.h (no remaining uses in the file)
and this branch's Formats/ParseError.h, which isJSONPathFilterSafe needs for the
isParseError-scoped catch. src/Functions/FunctionsComparison.h auto-merged - master's
change there is in the array-element Nothing path, not the Enum literal branch.

No change to this PR's content: for 7 of the 8 files the per-file patch-id is identical
before and after the merge, and for the conflict-resolved file only the hunk header and
context lines moved (the added and removed lines are byte-identical). Diffstat is unchanged
at 8 files, +464/-9, and isJSONPathFilterSafe still has exactly its 2 callers.

Verified on the merged tree: full rebuild clean, both new tests pass 50/50 randomized runs,
and 01515_force_data_skipping_indices, 04049_statistics_enum_invalid_value,
04327_107032_like_without_wildcards_pk_range, 04327_enum_value_out_of_range and
00944_minmax_nan are green. The four failures in a 37-test JSON-index breadth run fail
identically on a pristine master binary (single-node sandbox: no test_cluster_two_shards,
no ZooKeeper, no 127.0.0.2).


/// Like convertFieldToType, but a literal with no representation in the index type yields a null
/// Field instead of throwing: every caller already treats null as "the index cannot be used".
static Field convertFieldToIndexType(

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 leaves one Enum carrier behind: the new tolerant conversion is used for plain scalar predicates, has / hasAny / hasAll, mapContains, and JSON paths, but the arrayElement(map, key) = value / map.key_* = value branch below still feeds const_value straight into BloomFilterHash::hashWithField. On INDEX mapValues(m) TYPE bloom_filter over Map(String, Enum8('a' = 1, 'b' = 2)), m['k'] = 'zzz' will therefore hit hashWithField(Enum8, String) and throw during index analysis instead of declining the atom; the mapKeys side on Map(Enum8(...), T) has the same problem, and the rewritten subcolumn form can throw even earlier in tryParseMapSubcolumn. This branch needs the same tolerant conversion / decline behavior as the other bloom-filter Enum sites.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on the fix binary (Build ID b4b2819e) and a pristine master binary (594b0c0e). The line is real, but it is not this PR's defect, and the proposed remedy does not work.

MergeTreeIndexBloomFilter.cpp:998 does pass const_value to hashWithField unconverted, confirmed by stack trace. Four corrections:

  • Base-identical. That line is byte-identical to master's :980 and is not in this PR's changed path. Every arm below throws the same code and message on both binaries.
  • Not the non-member-literal defect. The error is Code 170 BAD_GET ("has String, requested Int64"), not Code 691. A valid member throws too: on Map(String, Enum8('a' = 1, 'b' = 2)) with INDEX mapValues(m) TYPE bloom_filter, m['k'] = 'a' fails identically to m['k'] = 'zzz'. A tolerant conversion for non-member literals cannot fix a predicate whose literal is a member.
  • Not Enum-specific. Valid values only, same index: Enum8 and DateTime throw 170 ("has String, requested UInt64" for the latter), while String, FixedString(3), UInt8 and LowCardinality(String) all return correct counts.
  • convertFieldToIndexType would not help. BAD_GET is not in isParseError() (src/Formats/ParseError.cpp), so it would rethrow unchanged. The site needs the type conversion it never had, not a tolerant decline.

The mapKeys claim never reaches index analysis: m['zzz'] on Map(Enum8(...), UInt64) is rejected by arrayElement itself with Code 43 ILLEGAL_TYPE_OF_ARGUMENT, identically for a valid key. With a correctly typed key it returns the right answer on both binaries, via :662, whose field is already deserialized through the index key type.

The subcolumn claim is unreachable from SQL: m. + backtick-k is Code 47 UNKNOWN_IDENTIFIER. That name is produced internally by FunctionToSubcolumnsPass::optimizeFunctionArrayElementForMap, which gates on tryInsert into the map key type (FunctionToSubcolumnsPass.cpp:209), so a key that cannot be parsed never becomes a subcolumn name. Where the rewrite does fire it lands on the same :998 (measured identical with optimize_functions_to_subcolumns 0 and 1).

Causal control: SETTINGS use_skip_indexes = 0 returns the correct counts for both throwing arms, so index analysis is the site.

Not folding it into this PR: it is a different root cause (a missing conversion that rejects valid values), it is broader than Enum, and this PR is already +464 and under review. I am raising it separately, the same shape as #110038 for the token-index family.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correcting my own last paragraph: I said I would raise this separately. That was wrong, and I should have checked my own open PRs first.

#107076 already fixes exactly this site, and it is mine. It replaces const_value = value_field in the has_values_index branch with convertFieldToType(value_field, *values_index_value_type, value_type.get()), declining the atom on a null result or a non-propagating throw, and it ships 04327_map_bloom_filter_index_fixed_string_default.sql whose fixture is literally map Map(String, Enum8('one' = 1, 'two' = 2)) with a mapValues bloom filter. That test is OK 1292 times across CI on #107076 (1 FAIL, 13 SKIPPED). Because the conversion is generic rather than Enum-specific, it covers the DateTime carrier I measured as well.

So the correct disposition for the line you flagged is: already fixed in flight by #107076, no new work, nothing to fold into this PR.

Everything else in my previous reply stands as measured: the line is base-identical and outside this PR's changed path, the failure is Code 170 BAD_GET on valid members rather than Code 691 on non-members, convertFieldToIndexType alone would not fix it since BAD_GET is not in isParseError(), and the mapKeys and map.key_* specifics are unreachable for the reasons given.

One correction in your favour on scope: the mapKeys side of that same branch (has_keys_index, :662) is genuinely untouched by #107076. It needs nothing today because map_info->key_field is deserialized through the index key type by tryResolveMapIndexInfo, and I measured a correctly typed key returning the right answer on both binaries, but that is a narrower reason than the one I gave.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for c849bc7

CI is fully finished on this head and there are no failures to own: 177 checks, 160 success,
17 skipped, 0 failure. Config Workflow and Finish Workflow both concluded success, and the
praktika report for this head has 0 dropped jobs, so the run carries real coverage rather than a
silently dropped matrix. Every skip has a stated reason (not affected by the changed files,
reused from cache, pr-performance / ci-toolchain label gates, no integration or Keeper
changes).

CIDB agrees: 0 rows with test_status IN ('FAIL','ERROR') at this commit.

Check / test Reason Owner / fixing PR
(none) no failing check on this head n/a

This is the first ledger covering the head produced by the 2026-08-13 master merge; the two
earlier ledgers on this PR cover 6505d0c4 and 377c9193.

Session id: cron:our-pr-ci-monitor:20260813-213000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@nihalzp

nihalzp commented Aug 19, 2026

Copy link
Copy Markdown
Member

Let's merge with master and fix conflicts.

Master rewrote the four bloom-filter call sites this branch had made tolerant of
non-member Enum literals. Two changes landed in the same lines:

- 55a52d8 / ec1641c / cc4ad33 introduced
  coerceStringFieldLikeSearchFunction, searchFunctionCoercesConstant and
  convertConstantForArrayIndexFunction, and gave createColumnFromConstantArray
  two more parameters, so the `has`/`indexOf`, `hasAny`/`hasAll` and
  `mapContains*` sites now pick a coercion mode before converting.
- This branch had replaced the bare convertFieldToType at those sites with
  convertFieldToIndexType, which turns a parse error into a null Field so the
  caller declines the atom instead of throwing during index analysis.

Resolution keeps master's coercion logic verbatim and routes only its four
remaining convertFieldToType calls through convertFieldToIndexType, so the two
fixes compose: the coercion decides which stored form to hash, and the tolerant
conversion decides whether the literal has a stored form at all. The
FixedString-width early declines master added are left ahead of the conversion,
where they short-circuit without needing it.

The index carries no submodule pin changes; the resolved tree's src diff against
master is byte-identical in size to this branch's pre-merge content
(8 files, +464/-9).

Requested by @ nihalzp on the pull request.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master in and resolved the conflict: 9fac699. The PR is MERGEABLE again.

The conflict was in MergeTreeIndexBloomFilter.cpp: master's bloom-filter commits (55a52d8, ec1641c, cc4ad33, 04833e0, a4fcc25) rewrote the same four call sites this branch had made tolerant of non-member literals, introducing coerceStringFieldLikeSearchFunction / convertConstantForArrayIndexFunction and two extra parameters on createColumnFromConstantArray.

I kept master's coercion logic verbatim and routed only its four remaining convertFieldToType calls through convertFieldToIndexType. The two fixes are orthogonal and compose: the coercion decides which stored form to hash, the tolerant conversion decides whether the literal has a stored form at all. Master's FixedString-width early declines stay ahead of the conversion, where they short-circuit without needing it.

Verified on the merged tree (build ID 2ceea35fda5f9380bdbd67899f632f5e93bd0343, asserted on binary and server): clean build; the six test files master added for those commits all pass (04654, 04836, 04846, 04847, 04872, 04907) along with this branch's two and the four prescribed oracles, 12/12; both new tests 50/50 under randomization.

Mutation control, so that green is not vacuous: reverting just those four sites to the plain convertFieldToType reddens 04862_enum_non_member_literal_key_analysis with Code: 691 UNKNOWN_ELEMENT_OF_ENUM, and leaves convertFieldToIndexType an unused function, which confirms those four are its complete set of callers with no dead plumbing.

The committed tree carries no submodule pin changes, and its diff against master matches the pre-merge content exactly (8 files, +464/-9).

The regression only exercised the key side of a Map. traverseTreeEquals reads the
element type from getValueType() for mapContainsValue and from getKeyType() for
mapContainsKey/mapContains, so the value side reaches the tolerant conversion
through a distinct path and could regress without the test going red.

Adds mapContainsValue over Map(String, Enum8) with a mapValues bloom_filter, and
the mapContainsKey spelling on the existing key-side table. Both a member and a
non-member literal are asserted, together with the use_skip_indexes = 0 control
and the force_data_skipping_indices index-usability pins, so an over-broad
decline cannot leave the result counts unchanged.

Measured against a pristine master binary: every new non-member assertion fails
there with UNKNOWN_ELEMENT_OF_ENUM and passes on this branch, while the member
assertions agree on both, so the added coverage is not vacuous.
Merged at 573230b.

One conflict, in MergeTreeIndexBloomFilter.cpp at the scalar equality site.
Master gained the zero-padding soundness guard from ClickHouse#112639 there, which declines
the index when a String or FixedString constant's padded match family does not
collapse to a single stored value, and it calls convertFieldToType after that
check. This branch replaced the same call with convertFieldToIndexType, which
maps a parse error to a null Field so a literal outside the index type marks the
index unusable instead of throwing.

Resolved by keeping master's guard verbatim and applying only this branch's
change to the conversion call. The two compose: the guard returns early before
any conversion happens, and the tolerant conversion differs from the strict one
only on the path that used to throw.

Every added and removed line of this branch's diff is byte-identical before and
after the merge (504 lines, same checksum); the merged tree differs from master
only in the eight files this branch owns.
isJSONPathFilterSafe declined the JSONAllPaths index whenever convertFieldToType
returned a null Field. That case is a literal with no exact representation in the
cast target, such as CAST(j.a AS UInt8) = 999, and it is unrelated to the throw
this branch fixes: before this branch the same predicate kept the index, so the
extra clause was a regression. With force_data_skipping_indices naming the index
it turned a query that returned zero rows into Code 277 INDEX_NOT_USED, and the
test pinned that error as expected behaviour.

Only a thrown conversion now declines the index, which is what the Enum literal
needs. A null Field never reaches either caller: both use the bool and read the
path name, not the converted value.

The two numeric arms cover both index conditions that share the helper, and they
assert the index stays usable. Restoring the clause makes them fail with Code 277
at the first one.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master at 573230bfe668dad. One conflict, in MergeTreeIndexBloomFilter.cpp: master gained the zero-padding guard from #112639 at the scalar equality site, and this branch replaced the conversion call on the same line. I kept master's guard verbatim and applied only the conversion change, so both hold; every added and removed line of this branch's diff is byte-identical before and after the merge.

I also removed an unintended change of my own. isJSONPathFilterSafe declined the JSONAllPaths index whenever convertFieldToType returned a null Field, which happens for a literal with no exact representation in the cast target such as CAST(j.a AS UInt8) = 999. Master keeps the index usable there, so with force_data_skipping_indices naming the index my version turned a 0-row answer into Code 277 INDEX_NOT_USED, and the test pinned that error as expected. Only a thrown conversion declines the index now, which is all the Enum literal needs; the two numeric arms assert usability across both index conditions that share the helper.

Noticed but not raising: validate_enum_literals_in_operators = 1 is ineffective for <=> and isDistinctFrom on a Nullable Enum operand. It measures identically on master and on this branch, so this PR does not change it.

The three conversion sites this branch made tolerant tested the thrown code with
isParseError, which accepts 19 codes. Only UNKNOWN_ELEMENT_OF_ENUM is in scope,
so the other 18 were swallowed too: an unparseable Date, DateTime, DateTime64,
IPv4, IPv6, UUID or number literal, and INCORRECT_DATA or ARGUMENT_OUT_OF_BOUND,
stopped propagating out of key and index analysis and silently returned no
condition instead.

The gtest FormatSharedInit.FilterInfoDoesNotLeakCallerContext reported this. It
builds equals(dt, 'not-a-datetime') on a DateTime64(3) key and asserts that
initKeyConditionOnce throws, which is the shape from the report the test was
written for. CANNOT_PARSE_DATETIME is an isParseError code, so the atom returned
false, the shared init no longer threw, and the test failed on all three
sanitizer builds.

Each site now compares against UNKNOWN_ELEMENT_OF_ENUM directly, so every other
code keeps the behaviour it has on master. This also drops the Formats/ParseError.h
include from three storage translation units, which no longer classify errors on
behalf of the formats layer.

Verified in both directions with the build id asserted to move. Before: the gtest
fails at the FAIL() on caller 1. After: both FormatSharedInit cases pass and both
04862 tests still match their reference byte for byte, 127 and 25 lines. A master
binary, which has no catch at all, dies on the first non-member comparison with
Code 691 after 6 of the 127 lines, so the narrowed catch is still what carries the
Enum literal.
@groeneai

Copy link
Copy Markdown
Collaborator Author

The Unit tests failure on the previous commit was caused by my own diff, not by a flake, and is fixed in 9fda16ef946b553.

I had scoped the three tolerant conversions with isParseError, which accepts 19 error codes. Only UNKNOWN_ELEMENT_OF_ENUM is in scope here, so the other 18 were swallowed as well: an unparseable Date, DateTime, DateTime64, IPv4, IPv6, UUID or number literal, plus INCORRECT_DATA and ARGUMENT_OUT_OF_BOUND, stopped propagating out of key and index analysis.

FormatSharedInit.FilterInfoDoesNotLeakCallerContext caught exactly that. It builds equals(dt, 'not-a-datetime') on a DateTime64(3) key and asserts the shared init throws; CANNOT_PARSE_DATETIME is an isParseError code, so the atom returned false, nothing threw, and the test failed on all three sanitizer builds. Each site now compares against UNKNOWN_ELEMENT_OF_ENUM directly, so every other code behaves as it does on master. This also drops the Formats/ParseError.h include from three storage translation units.

Verified in both directions on a debug build with the build id asserted to move: before, the gtest fails on caller 1; after, both FormatSharedInit cases pass and both 04862 tests still match their reference byte for byte, 127 and 25 lines. A master binary, which has no catch at all, stops at the first non-member comparison with Code: 691 after 6 of the 127 lines, so the narrowed catch is still what carries the Enum literal.

I corrected the description, which still described the wider isParseError scope.

}
catch (const Exception & e)
{
if (e.code() != ErrorCodes::UNKNOWN_ELEMENT_OF_ENUM)

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 unconditional UNKNOWN_ELEMENT_OF_ENUM catch weakens validate_enum_literals_in_operators = 1 on every planner-only path that goes through KeyCondition. With force_primary_key = 1 or force_index_by_date = 1, the atom now becomes FUNCTION_UNKNOWN, so ReadFromMergeTree.cpp:3294 / MergeTreeDataSelectExecutor.cpp:712 can throw INDEX_NOT_USED before row evaluation ever gets a chance to raise the validation exception. The same regression is repeated in MergeTreeIndexBloomFilter.cpp:717 and MergeTreeIndexJSONSubcolumnHelper.cpp:145 for force_data_skipping_indices.

Please rethrow UNKNOWN_ELEMENT_OF_ENUM when validate_enum_literals_in_operators is enabled, and add a focused regression check for the forced-index settings. For example, SELECT count() FROM t_key WHERE e = '4' SETTINGS validate_enum_literals_in_operators = 1, force_primary_key = 1 should still fail with UNKNOWN_ELEMENT_OF_ENUM, not INDEX_NOT_USED.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured on this head (9fda16ef) against the master snapshot this branch merged (82cfa6a).

The example does not reproduce. SELECT count() FROM t_key WHERE e = '4' SETTINGS validate_enum_literals_in_operators = 1, force_primary_key = 1 returns a byte-identical Code: 691 ... UNKNOWN_ELEMENT_OF_ENUM ... while executing function equals ... Const(size = 0, ...) on both arms, and so do the force_index_by_date and force_data_skipping_indices variants at all three sites cited, including the JSONAllPaths one. With the setting on, FunctionComparison<EqualsOp>::executeWithConstString throws while the planner dry-runs the filter header (FilterStep construction through ActionsDAG::updateHeader, hence the zero-row block in that message), which is upstream of every index condition, so none of the three catches is reached. EXPLAIN indexes = 1 and an empty table throw identically, so it is not row evaluation either. The one FunctionsComparison.h change here deletes an early return that sat before the setting check and applied only to !=, so the setting's own path is untouched.

The mechanism does appear where the comparison is not const-folded into the filter step: WHERE e = (SELECT '4') with those two settings gives INDEX_NOT_USED here and gave UNKNOWN_ELEMENT_OF_ENUM on master. I am keeping that, because a planning-time forced-index guard reporting before execution is not new: on master the identical subquery form already returns INDEX_NOT_USED when the Enum column sits outside the primary key, as does any unanalyzable predicate that would throw at row evaluation, for example WHERE throwIf(x > 0, 'boom') with force_primary_key = 1. With no index forced that shape still throws 691 here, and nothing turns a throw into a successful query: with the primary key actually used, execution reaches row evaluation and throws 691.

I did not add the suggested check. It returns 691 on master and on this head, with and without the rethrow proposed, so it cannot detect the behaviour it would protect.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9fda16e

CI is fully finished at this commit. One check failed, and it has an owner.

Check / test Reason Owner / fixing PR
Docs examples / Documentation examples trunk-side: tests/docs_examples/known_failures.txt:50 still names Function/catboostEvaluate#0, which stopped existing when the CatBoost integration was removed, so the job reports 1 known failure(s) no longer exist and must be removed #116566 (external, merged 2026-08-26 20:09:12Z) restores src/Functions/catboostEvaluate.cpp, so that entry is valid again. This leg ran at 19:14:11Z, before that merge, so the fix arrives with the next master merge here

Mergeable Check and PR are aggregate statuses rolling up that same single failure, not separate ones.

Not caused by this PR: the diff touches KeyCondition, FunctionsComparison.h, two MergeTree index helpers and two stateless tests, nothing under tests/docs_examples/ and nothing CatBoost. Over the last 30 hours the same message appears in 57 Docs examples rows, 4 of them on master (latest f10973ea7e22, 21:19:06Z) and 53 across 49 distinct pull requests, of which this PR contributes 1. Master measures both directions: Docs examples was OK at 14:24Z and 14:51Z, before the removal, and has failed on every master run since 16:29Z.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114035&sha=9fda16ef946b553fde13e3aa8d2432487c07e145&name_0=PR&name_1=Docs%20examples

Session id: cron:our-pr-ci-monitor:20260826-220000

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9c3a8f1

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
Stateless tests (arm_asan_ubsan, azure, sequential) / 04648_distributed_plan_task_error_propagation flaky, and not reproducible in its own rerun loop (0 of 3 reruns failed): the recorded CANNOT_SCHEDULE_TASK is lost and the client sees code 1000 instead of the expected 439. 66 pull requests and 16 true-master runs in the last 30 days. #118390 (mine, open), #118417 (external, open)
Stateless tests (arm_asan_ubsan, azure, sequential) / 04340_distributed_plan_status_reenqueue_fault flaky, and not reproducible in its own rerun loop (0 of 3 reruns failed): reference diff on the reenqueue fault handled line. 58 pull requests and 9 true-master runs in the last 30 days. #118417 (external, open), #118390 (mine, open)
PR praktika workflow rollup of the two rows above, no independent cause #118390 (mine, open), #118417 (external, open)

Session id: cron:our-pr-ci-monitor:20260908-170140

@vdimir

vdimir commented Sep 28, 2026

Copy link
Copy Markdown
Member

Fixing in #122672

@vdimir vdimir closed this Sep 28, 2026
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

5 participants