Repository navigation
Convert an Enum constant to its name, not its number, when comparing with a String column - #112647
Conversation
An Enum8 or Enum16 constant compared with a String or FixedString column was converted to the enum's underlying number instead of its name. convertFieldToTypeImpl had a String to Enum case (via IDataTypeEnum::castToValue) but no case for the other direction. An enum constant arrives as a numeric Field, so the target-is-string branch handled only Field::Types::String and everything else fell through to applyVisitor(FieldVisitorToString(), src), which stringified the number. The converted constant was '1' rather than the name 'V0', and every consumer that builds a point, range or hash from that Field used the wrong bytes. EXPLAIN indexes = 1 showed Condition: (v in ['1', '1']). Five surfaces returned wrong results, all on ordinary SELECT statements with no forced index: primary key and PARTITION BY pruning dropped matching rows, the bloom_filter skip index dropped them, IN and the values table function matched and inserted the wrong value, NOT IN was inverted and returned the row it should have excluded, and the OR-chain to IN rewrite silently dropped a disjunct. Since CAST(enum AS String) has always produced the name, = and IN disagreed on the same constant, which is what makes this a bug rather than a convention. Resolve the name through IDataTypeEnum::castToName, mirroring the existing inverse case, then re-enter convertFieldToTypeImpl so a FixedString target still zero-pads the name to its width. The source type hint is unwrapped first because only the target type is unwrapped by the caller, and Nullable(Enum) reaches this code with the wrapper still attached. Fixing the primitive corrects every consumer at once, and pruning is preserved: an enum constant now reads the same granule count as the equivalent String literal. An enum element inside an Array, Tuple or Map is still converted to the number, because the container recursion passes no element type hint down. That propagation is being added by ClickHouse#110084, so it is not duplicated here; three test cells assert the current behaviour so the gap cannot rot silently.
Review round 1, test only. The source fix is unchanged and the binary relinks to the same build id. The OR chain cell never exercised the OR to IN rewrite. That rewrite needs at least optimize_min_equality_disjunction_chain_length disjuncts, which defaults to 3, so the two disjunct chain stayed an OR of two equals and only re-measured what the plain equality cell already covers, while the description advertises the rewritten form. It now uses three disjuncts, keeping the default configuration under test rather than lowering the threshold, and a new cell asserts the rewritten query tree really contains an in function and no or. Removing the third disjunct again reddens that new cell and nothing else. Nine promised index surfaces were asserted on their results only, which cannot see a regression that restores correctness by declining the index: a declined index reads every granule and still returns the right rows. Ten cells now compare the enum constant's granule total against the equivalent string literal's, one per distinct conversion branch, plus three companions requiring that granules really are skipped so both arms reading everything cannot satisfy the equality. Two fixtures grew to make those oracles meaningful. The FixedString table had two rows, where a point lookup reads every granule on both arms. The partitioned table had equally sized partitions, so the wrongly selected partition had the same granule count as the correct one and the cell would have been a guard rather than a detector. The test now has 44 cells, 31 of which fail before the fix. Co-Authored-By: Claude Fable 5 <[email protected]>
…rd enum free Fix round 2, test only. Both changes are on the or_chain_is_rewritten cell added in round 1. EXPLAIN QUERY TREE throws NOT_IMPLEMENTED when the analyzer is disabled, and that is a query error, so it aborted the whole file rather than reddening one cell: under the old analyzer the run stopped at cell 16 and produced 15 of 44 cells. The test carries no tags, so neither the dedicated old analyzer job nor compatibility settings below 24.3 were defended against. A statement level SETTINGS clause on the outer SELECT fixes both routes while leaving the other 43 cells their old analyzer coverage, which a session SET or a no-old-analyzer tag would have deleted. The clause cannot sit on the inner subquery: applySettingsFromSelectWithUnion reads only the last top level SELECT's settings, so the context stays false and validateAnalyzerSettings then rejects the inner clause as a setting changed in a subquery. The cell's three disjuncts are now plain String literals instead of enum constants. It exists to guard the chain length that or_chain_rewritten_to_in depends on, so that a future edit cannot drop the chain below optimize_min_equality_disjunction_chain_length and make the behavioural cell vacuous again. Measuring that with enum constants also made it depend on whether an enum constant is eligible for the rewrite at all, which is a separate question that rewrite eligibility rules may legitimately change. With plain literals the cell reads 1 both before and after this branch's source fix, which is what makes it a mechanism guard rather than a bug detector. or_chain_rewritten_to_in keeps its three enum disjuncts and remains the enum detector, so enum correctness is asserted behaviourally and chain length structurally. Source, reference file and build are untouched.
…ng test An equality-only pruning oracle compares the enum arm's selected-granule total against the equivalent String literal's, and two full scans are equal, so such a cell still passes when the index declines for both operands. That is the exact regression the change is supposed to rule out, because restoring correctness by making a branch give up on the index would silently cost pruning while every result cell stayed green. Seven surfaces were still equality-only. Six of them gain a selected < total companion. Those six are guards rather than detectors: they also read 1 on unfixed master, where the constant still narrows the read but narrows it to the wrong granule. A comment records that, so a permanently green cell is not later mistaken for a vacuous one. PARTITION BY gets a condition-text oracle instead. A declined index still lets the Min-Max section prune parts there, so a granule-count companion would not cleanly fail, and reading the condition is stronger anyway: it names the value key analysis used, which detects the name-versus-number substitution directly. Both the Min-Max and the Partition section print the condition, hence a positive-count threshold rather than an exact count. Verified in both directions and mutation tested: reverting the source hunk reproduces the pristine classification byte for byte, weakening one companion's comparison to <= leaves it green so < is the load-bearing operator, and pointing the condition-text oracle at a literal absent from the plan flips exactly that one cell.
Internal second-model reviewThis PR went through four independent review rounds before publication. Each round ran a cold Fixed during review
Refuted with evidence
Noted, not blocking
Session id: cron:clickhouse-review-slot-52:20260730-180300 |
Pre-PR validation gate
Mutation tests, each source mutation built with a verified distinct Build ID: deleting the new case reddens all 32 detector cells; using 50 randomized parallel runs of the new test: 50 OK, 0 FAIL. The test carries no tags; it needs no external resource and all object names are scoped to the implicit per-test database. |
|
cc @Avogar @rschu1ze, could you review this? |
|
Workflow [PR], commit [8a69563] Summary: ✅
AI ReviewSummaryThis PR fixes the core Findings❌ Blockers
Tests
Final Verdict❌ Changes needed before merge. The primitive fix is correct, but the PR still leaves wrong-results paths in shard pruning, partition targeting, key-value direct lookup, and JSON path skip-index safety, so it does not yet deliver the promised end-to-end bug fix. |
| } | ||
|
|
||
| /// Re-enter so that a `FixedString` target still zero-pads the name to its width. | ||
| if (const auto * enum_from_type = dynamic_cast<const IDataTypeEnum *>(unwrapped_hint)) |
There was a problem hiding this comment.
convertFieldToType is fixed here only for callers that still carry from_type_hint, but the analyzer-side shard-pruning rewrite still drops that hint and can therefore return wrong results on Distributed tables with a String sharding key. In OptimizeShardingKeyRewriteInVisitor::shardContains we still do convertFieldToType(column_value, *column_type) at src/Interpreters/OptimizeShardingKeyRewriteInVisitor.cpp:53, so CAST('7', 'Enum8(''7'' = 3)') is still interpreted as '3' when deciding which shard owns a value. Then the query-tree path rebuilds the surviving RHS as ConstantNode(new_tuple) at src/Interpreters/OptimizeShardingKeyRewriteInVisitor.cpp:194, which infers Tuple(Int64, ...) and strips the enum element types entirely. With allow_experimental_analyzer=1 and optimize_skip_unused_shards_rewrite_in=1 both defaulting to true, a query like ... WHERE shard_key IN (CAST('7', 'Enum8(''7'' = 3)'), 'other') can still drop the shard that owns '7' or rewrite the remote query with plain numeric RHS values. This needs the same enum-name conversion in the shard rewrite path, plus preserving the surviving tuple's logical element types when re-creating the ConstantNode.
There was a problem hiding this comment.
Both halves are real and I verified them at the lines you cite: shardContains converts hintlessly at OptimizeShardingKeyRewriteInVisitor.cpp:53, and the rebuild at :194 passes no type so the Tuple(Enum8(...), ...) element types are re-inferred away. I am tracking that path as a separate fix, gated on this PR, rather than widening this one (one concern per PR).
Two corrections to the reachability, both measured.
The rewrite additionally needs optimize_skip_unused_shards, which defaults to false. Both call sites (ClusterProxy/executeQuery.cpp:420 and :459) require query_info.optimized_cluster, and that member has exactly one assignment tree-wide, StorageDistributed.cpp:542, enclosed by if (nodes > 1 && settings[Setting::optimize_skip_unused_shards]). So it is an opt-in setting plus a multi-shard Distributed table, not stock defaults.
The residue is also not live yet: git show origin/master:src/Interpreters/convertFieldToType.cpp | grep -c castToName is 0, so master has no Enum-source branch and a caller-side hint there would be a no-op until this PR lands. That ordering is why the follow-up is gated on this one.
This PR cannot affect that path. The new branch is guarded by dynamic_cast<const IDataTypeEnum *>(unwrapped_hint) derived from from_type_hint, all three shardContains call sites (:118, :130, :184) pass no hint, and from_type_hint defaults to nullptr (convertFieldToType.h:78), so a null hint fails the cast. Confirmed empirically on a hintless caller: ALTER TABLE ... DROP PARTITION CAST('V0', 'Enum8(''V0'' = 3)') against partitions ['3','V0'] leaves ['V0'] on both a pristine master build and this PR's build, byte-identical.
The follow-up will carry the enum-name conversion into shardContains and preserve the surviving tuple's element types when reconstructing the ConstantNode, with a rewrite-on versus rewrite-off oracle over a multi-shard fixture. I will post its link here when it opens.
There was a problem hiding this comment.
Closing the loop on my promise above: no separate PR is coming, for two measured reasons.
Both halves I confirmed are already implemented in @ alexey-milovidov's #110084, in this exact
file at these exact lines, generically: shardContains gains a from_type_hint parameter that
it forwards to convertFieldToType, the analyzer path threads per-element types from
assert_cast<const DataTypeTuple &>(*constant->getResultType()).getElements() under an
element-count guard, and the :194 rebuild becomes
ConstantNode(Field(std::move(new_tuple)), std::make_shared<DataTypeTuple>(std::move(new_element_types))).
Its motivation is UUID/UUID2, but the plumbing is type-agnostic and covers the Enum case.
And there is nothing user-observable to fix on master today. I ran 20 A/B cells on a two-shard
remote('127.{1,2}', ..., sipHash64(s)) cluster with optimize_skip_unused_shards = 1 and
optimize_skip_unused_shards_rewrite_in = 1, choosing Enum members whose name and number map to
different shards ('alpha' = 1, 'beta' = 4, 'gamma' = 8: name shard 2, number shard 1) so the
fixture cannot cancel itself out. Rewrite-on vs rewrite-off, and rewrite-on vs no-pruning-at-all
compared on distinct value sets, are byte-identical in every cell, across String / Int32 /
LowCardinality / Enum sharding keys, Enum16, mixed tuples, nested sharding expressions and the
legacy analyzer. A plain IN ('alpha','beta','gamma') control does match, so the harness can see
a real difference.
The reason is that master's convertFieldToType has no Enum-source branch, so pruning stringifies
the Enum's number and the Set filter on the shard does the same: materialize('3') IN (CAST('7', 'Enum8(''7'' = 3)')) returns 1 while materialize('7') IN (...) returns 0. Both halves
are wrong in the same direction, so pruning selects exactly the shard the filter would match.
Also worth recording: the legacy-analyzer path prunes nothing at all in this shape (6 rows with
the rewrite on and off alike), which matches the reasoning in #110084's comment for leaving the
AST side unhinted.
So the residual is a regression test over generic plumbing that does not exist yet, not a fix.
Not raising it.
The two pk_partition cells read the EXPLAIN indexes = 1 output, but without the analyzer the old interpreter answers count() from the partition predicate alone (InterpreterSelectQuery.cpp, "It's possible to optimize count() given only partition predicates"), which the analyzer declines to do (PlannerJoinTree.cpp returns early on hasWhere with that case left as a TODO). The plan then collapses to ReadFromPreparedSource (Optimized trivial count) and carries no Indexes section, so partition_key_condition_uses_name found no condition text and read 0, failing the old analyzer job, and partition_key_prunes compared 0 against 0 and passed vacuously while testing nothing. Both cells now pin the optimization off, so both surfaces are measured under either analyzer. The conversion itself was already correct on both: the condition reads (v in ['7', '7']) post fix and (v in ['3', '3']) pre fix under the pin regardless of the analyzer, and the results agree with the reference table either way, so no source change is needed. Co-Authored-By: Claude Fable 5 <[email protected]>
The two pk_partition cells that read a plan pin optimize_trivial_count_query off, because without it the old analyzer answers count() from the partition predicate alone and the plan collapses to ReadFromPreparedSource with no Indexes section: the condition cell then found no text to match and read 0, which is the old analyzer job failure, and the granule cell compared 0 against 0 and passed while measuring nothing. Pinning the setting is correct for those two, but it silences the default route entirely, and that route is a separate consumer of the converted constant. It also fails differently. Where key analysis drops the matching row, answering count() from the partition predicate counts the wrongly selected partition instead, so on the unfixed server the enum constant returned 3 for a true count of 1 while groupArray over the same predicate returned nothing. A count and a row read disagreeing on one constant is a second symptom worth pinning, so the surface gets a count cell that leaves the optimization enabled. The granule cell gets a companion asserting the pinned plan carries granule counts at all, so the equality cannot degenerate to 0 = 0 again unnoticed. The conversion itself needs no change: with the fix the enum constant reads 1 on both routes under either analyzer. Co-Authored-By: Claude Fable 5 <[email protected]>
The runner disables optimize_trivial_count_query at random in roughly one run in twenty, and that is the route this cell exists to cover, so without a pin those runs silently fall back to key analysis, which three other cells already cover. Pinning the setting on keeps the route selected on the analyzer that takes it. The pin does not change what the cell reads: the count is wrong before the fix and right after it on either route, so no arm moves. Asserting that the route really was selected would need the plan, and the old analyzer cannot be pinned inside a subquery, so the cell asserts the count instead. Co-Authored-By: Claude Fable 5 <[email protected]>
… route The granule companion asserted only that some granule count was reported, which a full scan satisfies just as well as real pruning, so it now requires the plan to name a Partition section and to leave granules unread. On a predicate that cannot prune this reads 0 where the previous form read 1. The count cell covers the partition predicate route only while that route is selected, and only the old analyzer selects it, since the planner declines trivial count whenever a WHERE is present. An analyzer cannot be pinned inside a subquery, so a companion asserts that route selection still follows the analyzer in use: it reads 1 on both analyzers today and turns 0 if the old analyzer stops taking the route, which is the case that would quietly reduce the count cell to an ordinary scan. Co-Authored-By: Claude Fable 5 <[email protected]>
Summing the ratios of every Indexes section let Min-Max pruning alone satisfy the companion, so it now reads the ratio out of the Min-Max section by name. Each stage's denominator is the previous stage's numerator, and on a partition key Min-Max narrows to the surviving partitions before the Partition stage runs, so that stage reports N/N for any predicate and is not assertable: measured 1/5 for Min-Max against 1/1 for Partition on the correct plan, and 10/40 against 10/10 on a larger fixture. The narrowed form fails on both of the cases that previously passed: a predicate that cannot prune reads 0 where the summed form read 1, and so does a plan with no Indexes section at all. Co-Authored-By: Claude Fable 5 <[email protected]>
Every stage's denominator is the previous stage's numerator, so on a partition key Min-Max narrows to the surviving partitions first and the Partition stage that follows reports 1/1 for any predicate: asserting on either the summed ratio or the Min-Max ratio let one stage's pruning stand in for the other's, and the condition text was matched anywhere in the plan rather than in one section. Adding use_skip_indexes = 0 leaves Min-Max inert at 5/5 with condition true and makes Partition the stage that prunes, measured at 1/5. Both cells now read that section by name, so removing the setting reddens the ratio cell and expecting the number instead of the name reddens the condition cell. Co-Authored-By: Claude Fable 5 <[email protected]>
Half the assertions read an index section out of EXPLAIN indexes = 1, and with parallel_replicas_local_plan = 0 the plan is a single ReadFromRemoteParallelReplicas node carrying no index section, so every extraction returns zero: the partition ratio cell reads 1 on a local plan and 0 on a remote-only one, and the runner randomizes that setting. The no-parallel-replicas tag both stops the runner from enabling parallel replicas for this test and skips it in the dedicated parallel replicas job, which is what 86 of the 171 stateless tests reading EXPLAIN indexes already do. The cost is that this test does not run in that one job; the conversion it covers is not parallel replicas specific, and every other job still runs it. Co-Authored-By: Claude Fable 5 <[email protected]>
The partition surface has three plan cells rather than two after this round. The enum name is one byte, so FixedString(1) fits it exactly rather than being narrower than it, which is what makes that cell a control and the FixedString(4) cell the padding test. And the pk_lc and pk_nullable cells carry the wrapper on the key type, not on the enum hint, so they do not exercise the source hint unwrap loop; the Nullable(Enum) cells further up are what cover that. Co-Authored-By: Claude Fable 5 <[email protected]>
… out The no-parallel-replicas tag removed all 54 assertions from the dedicated parallel replicas job, which is more than the problem needs: only the remote-only plan is hostile, because it is a single ReadFromRemoteParallelReplicas node with no index section, so every extraction reads 0. A session level SET enable_parallel_replicas = 0 stabilizes those assertions while keeping the test running everywhere. Measured against a forced remote-only plan the partition ratio cell reads 0 without it and 1 with it, and the test now runs rather than skips in that job. Also corrects the last stale count in the commentary: three plan cells above the count cell disable the trivial count optimization, not two. Co-Authored-By: Claude Fable 5 <[email protected]>
| } | ||
|
|
||
| /// Re-enter so that a `FixedString` target still zero-pads the name to its width. | ||
| if (const auto * enum_from_type = dynamic_cast<const IDataTypeEnum *>(unwrapped_hint)) |
There was a problem hiding this comment.
convertFieldToType is fixed here only for callers that still preserve the enum source type, but ALTER ... PARTITION still discards that type before it reaches this branch. In MergeTreeData::getPartitionIDFromQuery, both the single-field and tuple paths call evaluateConstantExpression(...).first and then convertFieldToTypeOrThrow(..., target_type) at src/Storages/MergeTree/MergeTreeData.cpp:8584, :8597, and :8613. For a String partition key, CAST('V0', 'Enum8(''V0'' = 3)') still arrives here as Int64(3) with no from_type_hint, so the resolver builds '3' instead of 'V0'. That means DROP / DETACH / MOVE PARTITION can still target the wrong partition. The fix needs to thread the DataTypePtr returned by evaluateConstantExpression into convertFieldToTypeOrThrow, including the per-element hints for tuple partition keys.
| } | ||
|
|
||
| /// Re-enter so that a `FixedString` target still zero-pads the name to its width. | ||
| if (const auto * enum_from_type = dynamic_cast<const IDataTypeEnum *>(unwrapped_hint)) |
There was a problem hiding this comment.
convertFieldToType is still blind on the key-extraction path for the key-value engines. getFilterKeys in src/Storages/KVStorageUtils.cpp converts equality and tuple-key values with convertFieldToType(..., target) at :140, :292, and :376, but never passes the source type from the constant column / set elements. For Redis, KeeperMap, and EmbeddedRocksDB, WHERE key = CAST('7', 'Enum8(''7'' = 3)') on a String primary key still probes '3' instead of '7', and composite-key tuple filters have the same problem for string components. This is a wrong-results path, not just a missed optimization: these storages switch from full scan to direct point lookups based on getFilterKeys. The fix needs to preserve the constant's type when extracting the key fields.
There was a problem hiding this comment.
Both findings are real and I verified them at the lines you cite. MergeTreeData.cpp:8584/:8597 (simple key) and :8602/:8613 (complex key) discard the type from evaluateConstantExpression, and all three convertFieldToType calls in KVStorageUtils.cpp (:140, :292, :376) are hintless. I am tracking both as separate fixes rather than widening this one (one concern per PR).
Finding 1 is wider than you state: getPartitionIDFromQuery is the shared resolver, so besides DROP/DETACH/MOVE PARTITION it also mis-resolves ALTER ... UPDATE ... IN PARTITION (MutationsInterpreter.cpp:270, :344, :346) and OPTIMIZE ... PARTITION. The follow-up covers the per-element tuple hints you ask for. Measured on this PR's build versus a pristine master build, both with buildId() asserted against the ELF note: with partitions ['3','7'], DROP PARTITION CAST('7', 'Enum8(''7'' = 3)') leaves ['7'] on both, and the tuple form DROP PARTITION (CAST('7', ...), 1) leaves [('7',1)] on both. Byte-identical, so that path is untouched here.
One correction on finding 2: the IN routes are already fixed by this PR, and master is worse there than you describe. On EmbeddedRocksDB with a String primary key, where the correct answer is the '7' row in every cell:
| cell | pristine master | this PR |
|---|---|---|
k = '7' (control) |
[('7',7)] |
[('7',7)] |
k = CAST('7','Enum8(''7''=3)') |
[] |
[] |
k IN (CAST('7','Enum8(''7''=3)')) |
[('3',3)] |
[('7',7)] |
(a,b) = (enum,'x') |
[] |
[] |
(a,b) IN ((enum,'x')) |
[('3','x',3)] |
[('7','x',7)] |
So on master the IN form returns the wrong row rather than no row, and this PR fixes both IN cells without touching KVStorageUtils.cpp: set construction already converts with a live hint upstream at src/Analyzer/SetUtils.cpp:92, so fields arriving at :376 already carry the name. The remaining residue on that file is the scalar = path at :140 and the tuple-equality path at :292.
That residue is already threaded by #110084, which adds a getSourceTypeHint helper and passes it at all three sites including the per-element tuple types, so writing it again here would duplicate a file that PR is rewriting. The two changes are complementary: #110084 supplies the hints and adds no Enum handling of its own, while this PR teaches the helper to use an Enum hint. git merge-tree on the two heads reports no conflict.
This PR cannot reach either path: the new branch is guarded by dynamic_cast<const IDataTypeEnum *>(unwrapped_hint) derived from from_type_hint, every caller you cite passes no hint, and that parameter defaults to nullptr. Ordering is also why the follow-ups are gated on this PR rather than landing first: castToName does not yet appear in convertFieldToType.cpp on master, so a caller-side hint is inert until this lands.
I will post the follow-up link here when it opens.
CI finish ledger - b4aacd3Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The failure is not caused by this PR, whose diff is one Session id: cron:our-pr-ci-monitor:20260801-093000 |
| } | ||
|
|
||
| /// Re-enter so that a `FixedString` target still zero-pads the name to its width. | ||
| if (const auto * enum_from_type = dynamic_cast<const IDataTypeEnum *>(unwrapped_hint)) |
There was a problem hiding this comment.
convertFieldToType is fixed here only for callers that preserve the enum source type, but the JSONAllPaths skip-index safety check still drops that hint. isJSONPathFilterSafe does convertFieldToType(value_field, *key_expression_type) at src/Storages/MergeTree/MergeTreeIndexJSONSubcolumnHelper.cpp:113, and both JSON-path bloom-filter callers (src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp:882 and src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp:453) rely on that result to decide whether it is safe to prune granules where the path is absent.
That is still wrong for typed string subcolumns with an empty enum label, which ClickHouse allows. For example, with json.a.:String = CAST('', 'Enum8('''' = 1, ''x'' = 2)'), the correct converted value is the empty string, so a missing path compares equal to the type default and JSONAllPaths must not skip absent-path granules. The hintless conversion sees Int64(1), turns it into '1', and incorrectly marks the predicate as safe, so rows where json.a is missing can be pruned away. This helper needs the same source-type hint threaded into it, e.g. by passing the RHS value_type from the caller and calling convertFieldToType(value_field, *key_expression_type, value_type.get()).
There was a problem hiding this comment.
The defect is real and I reproduced it. isJSONPathFilterSafe is hintless at MergeTreeIndexJSONSubcolumnHelper.cpp:113, and both callers you cite hold an unused value_type. It is tracked as a separate fix rather than widened into this one, alongside the partition-resolver and KV residue from the previous round.
Three corrections, because they change what the follow-up has to implement and test.
Your repro shape does not reproduce. You wrote json.a.:String. The typed-subcolumn syntax yields Nullable(String), so canContainNull returns true and the helper exits at :107 before reaching the hintless call. Only the ::String CAST form, which yields plain String, is a carrier:
toTypeName(data.a.:String) Nullable(String) -- immune
toTypeName(data.a::String) String -- carrier
toTypeName(data.a) Dynamic -- immune
data.a.:String = CAST('', 'Enum8('''' = 3)') returns [3] with and without the index. Anyone checking your query verbatim sees matching answers and closes the finding.
The ::String form on JSONAllPaths bloom_filter, rows (1,{"a":"x"}) (2,{"b":"y"}) (3,{"a":""}) (4,{}), truth [2,3,4]. Both arms buildId-asserted against the ELF note, pristine arm's carrier files md5-identical to master:
| cell | pristine master | this PR |
|---|---|---|
data.a::String = CAST('', 'Enum8('''' = 3)') indexed |
[3] |
[3] |
same, use_skip_indexes = 0 |
[2,3,4] |
[2,3,4] |
data.a::String = '' control, indexed |
[2,3,4] |
[2,3,4] |
EXPLAIN indexes = 1 shows the plain form leaving Granules: 4/4 with no Skip node while the enum form emits Name: idx_paths / Granules: 2/4. Byte-identical across arms, so it is pre-existing. This PR cannot reach it: the new branch is guarded by dynamic_cast<const IDataTypeEnum *>(unwrapped_hint) off from_type_hint, that call passes no hint, and the parameter defaults to nullptr.
The carrier set is wider than the two callers, and one sibling is immune by design. tokenbf_v1 and ngrambf_v1 both reproduce through BloomFilterText.cpp:453, so the follow-up owes cells for them. text does not, and the reason is worth adopting instead of threading a hint: MergeTreeIndexConditionText::traverseJSONSubcolumnKeyNode at MergeTreeIndexConditionText.cpp:1627-1636 never converts a Field. It builds required_column.type->createColumnConstWithDefaultValue(1), executes the real predicate DAG against it, and declines when the result is true. That evaluates actual comparison semantics, so no source type can be dropped and there is nothing to keep in sync. Threading value_type fixes the Enum case only; this shape is immune to the whole class.
One fixture warning. ngrambf_v1 first measured as immune with the 1-char path a. A 1-char path produces no 3-grams, so the index cannot prune and the cell passes for the wrong reason. With path alpha it reproduces. A test here needs a path at least as long as the n-gram size.
On scope for this PR: I enumerated all 60 convertFieldToType and convertFieldToTypeOrThrow call sites under src/. Two are hintless in the index layer this PR touches. KeyCondition.cpp:4192 is not a carrier, because it sits behind const_value.getType() == Field::Types::String at :4139 and an Enum constant is numeric, so it routes to the hinted tryConvertFieldToType at :4223. MergeTreeIndexBloomFilter.cpp:705 is a real carrier and is already pinned in this PR as known_limitation_has_any and known_limitation_has_all, attributed to the container-element axis in #110084. The JSON helper is a different layer.
Ordering is unchanged: castToName still does not appear in convertFieldToType.cpp on master, where the only enum reference is the opposite castToValue at :375, so a caller-side hint is inert until this lands. I will post the follow-up link here when it opens.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 13/13 (100.00%) · Uncovered code |
CI finish ledger - 8a69563CI is fully finished on this head and there is nothing to own: 174/174 check-runs completed, 156 success, 18 skipped, 0 failures.
Verified from the paginated check-runs API rather than the status rollup, which truncates on this repo. I am not re-pinging reviewers. Session id: cron:our-pr-ci-monitor:20260803-163000 |
|
@groeneai @alexey-milovidov @Avogar — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
Confirmed. I reproduced #117446 on a debug build of this PR's merge commit (
A fix task already owns the partition-resolver half, with a reviewed plan. I found the same hintless callers during this PR's own review on 2026-07-29 and deferred them out under one-concern-per-PR, so nothing changes on this merged PR. One addition to the affected list. On Nothing in the report is wrong or already addressed, so I am closing nothing. |
…nstant conversion An Enum8/Enum16 constant wrapped in Variant or Dynamic and compared against a String or FixedString column converted to the enum's underlying number instead of its name, so `IN` matched the wrong row, `NOT IN` was inverted, and key analysis pruned on the wrong value. `=` on the same constant was already correct, which is what showed this to be a bug rather than a convention. `convertColumnToTypeOrNull` reconstructs a Field from the constant's column and delegates to `convertFieldToType`. `ColumnVariant::get` returns the nested column's value and drops the discriminator, and `ColumnDynamic::get` delegates to it, so the Field no longer records which alternative was active while the source-type argument handed down is still the carrier's type. Every conversion in `convertFieldToType` that is keyed on the source type therefore took the wrong branch: the Enum-to-name case added by ClickHouse#112647 tests the hint with `dynamic_cast<const IDataTypeEnum *>`, which fails for `Dynamic`, so the value was rendered as its number. Read the alternative's type back from the column, which still records it, and pass that as the source type at both delegation points. `ColumnDynamic` exposes `getTypeAt`, covering the regular and the shared-variant storage; `ColumnVariant` stores no types of its own, so its global discriminator is resolved against the `DataTypeVariant` the caller already supplies. That also makes an ambiguous variant such as `Variant(Bool, UInt8)` faithful, which the header previously documented as impossible: it is impossible for the Field, not for the column. Fixed by the same change, each verified against the equivalent String-literal result: `NOT IN`, a set built from a collection element, a `FixedString` target, the shared-variant storage of `Dynamic`, `Bool` under `Variant`, and a `Date`/`DateTime` bound wrapped in `Dynamic`, which previously matched nothing at all. Pruning is preserved rather than traded for correctness.
Related: #110084
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes wrong results when an
Enum8orEnum16constant is compared with aStringorFixedStringcolumn. The constant was converted to the enum's underlying number instead of its name, so primary key andPARTITION BYpruning, thebloom_filterskip index,INandNOT INsets and thevaluestable function all used the wrong value. Matching rows were silently dropped,NOT INreturned the row it should have excluded, andINdisagreed with=on the same constant.Description
convertFieldToTypehad aStringtoEnumcase but no case for the other direction. An enum constant arrives as a numericField, so the target-is-string branch fell through toFieldVisitorToStringand stringified the number:v = CAST('V0', 'Enum8(''V0'' = 1)')becamev = '1'.EXPLAIN indexes = 1showedCondition: (v in ['1', '1'])where it now shows(v in ['V0', 'V0']).That
v = <enum>returned one row whilev IN (<enum>)returned a different one is the clearest sign this was a bug rather than a convention, sinceCAST(<enum> AS String)has always produced the name.The fix completes the missing half of the conversion pair in the primitive itself, mirroring the existing
StringtoEnumcase: resolve the name throughIDataTypeEnum::castToName, then re-enter so aFixedStringtarget still zero-pads the name to its width. The source type hint is unwrapped first, becauseNullable(Enum)reaches this code with the wrapper still attached. Fixing the primitive corrects every consumer at once, and pruning is preserved rather than traded for correctness: an enum constant now reads the same granule count as the equivalent String literal.Validated with a 54-cell regression test, red in 33 cells before the fix and fully green after under either analyzer; sixteen mutations each reddening exactly their own cells; a same-tree A/B over 1707 conversion-sensitive stateless tests with no reference output moved; and 50 randomized parallel runs of the new test.
One case is deliberately left out of scope: an enum element inside an
Array,TupleorMapis still converted to the number, because the container recursion passes no element type hint down. Cells pin the current behaviour of theArraymanifestation. That propagation is already being added by #110084, so it is not duplicated here.Version info
26.9.1.411(included in26.9and later)