Repository navigation
Conversation
has/indexOf/indexOfAssumeSorted/countEqual/mapContainsKey/mapContainsValue returned wrong results when the array element and the searched value had a type-erasing common type: has([1::UInt64]::Array(Dynamic), 1::UInt8) was 0 while 1::UInt64::Dynamic = 1::UInt8 is 1, and countEqual disagreed with the arrayCount(elem -> elem = x, arr) equivalence its own documentation states. Dynamic is production-ready, so no setting was needed to reach this. FunctionArrayIndex tested equality with IColumn::compareAt(...) == 0. For ColumnDynamic/ColumnVariant compareAt compares the variant type name (or discriminator) first and only then the value, so two equal values stored under different variants never compared equal and the row was skipped. compareAt defines a total order for sorting; using it as the equality relation is only sound where "same sort position" implies "equal", which erased columns break by construction. When the common type is type-erasing, evaluate the registered equals over the elements and fold the result per row instead. That is the relation `=` uses, and the one arrayRemove already uses on this data. A new executeArray dispatcher owns the array-shaped dispatch and is called from both entry points (executeImpl and executeMap), so all six FunctionArrayIndex instantiations are covered as constant, materialized and LowCardinality; the constant and LowCardinality arms answer before the generic path and diverged differently, so covering only one would have relocated the inconsistency rather than fixing it. The helper returns nullptr for every non-erased common type, leaving the existing specialised paths untouched, and the constant and LowCardinality-dictionary optimisations are preserved rather than materialized away. The guard recurses through Tuple but stops at Array/Map, because equality for two identical Array/Map types is itself compareAt-based: routing those shapes through the fix could not change their answer, only add work. That is also why the traversal is written explicitly over DataTypeTuple::getElements rather than IDataType::forEachChild, whose ChildCallback takes no parent and returns void and therefore cannot prune a subtree. Delegating inherits dynamic_throw_on_type_mismatch and variant_throw_on_type_mismatch instead of reimplementing them, so no setting is added and no SettingsChangesHistory entry is needed. The context the three registration routes already receive is now forwarded so those settings apply; the map adapter detects constructibility so its 16 unrelated instantiations are unaffected, and a null context yields equals with default ComparisonParams rather than failing. Two behaviour changes bring membership in line with `=`: a NULL needle against a materialized erased array holding a NULL now matches, restoring the documented has([NULL], NULL) -> 1; and Array(String) with a numeric Dynamic needle now raises NO_COMMON_TYPE rather than returning 0. The updated 04338 reference is that test's own stated invariant, that has(m, k) must agree with has(mapKeys(m), k) for every row, now holding. Co-Authored-By: Claude Fable 5 <[email protected]>
The previous commit folded a nested NULL to "no match", so
has(CAST([tuple(NULL::Dynamic)], 'Array(Tuple(Dynamic))'), tuple(NULL::Dynamic))
returned 0 where master returns 1 - a regression inside this change's own
contract, since it covers erasure nested in Tuple and restores
has([NULL], NULL) -> 1.
Two facts combine to cause it. ColumnTuple does not override isNullAt, so it
inherits IColumn's `return false` and a NULL nested in a Tuple is invisible to a
top-level nullness probe, while Dynamic, Variant, Nullable and LowCardinality
columns all report theirs correctly. And once any position of a row is NULL,
`equals` collapses the whole row to a single NULL, so its verdict cannot settle
the row's remaining positions either: Tuple(Dynamic, UInt8) rows (NULL, 1) and
(NULL, 2) pair their NULLs yet are not equal.
Decompose the Tuple and recurse instead, folding each position where its own
nullness is visible, then AND the per-position results. The recursion is
unbounded in depth and stops at Array/Map, matching hasTypeErasingElement, so
the container barrier and its declined controls are unaffected.
Delegating the row to isNotDistinctFrom was considered and rejected: it sets
useDefaultImplementationForVariant() to false and routes Nullable-vs-Nullable
through compareAt, which reinstates the ordering predicate this change exists to
replace. Measured, it returns 0 for 'V0'::Dynamic vs toFixedString('V0', 3)
where `equals` returns 1, and throws ILLEGAL_TYPE_OF_ARGUMENT for a Variant
needle. It is used only as the test oracle, where null-safety is what is wanted:
the `=` oracle cannot express these rows, because `=` over a Tuple holding a NULL
yields NULL and arrayExists reads non-true as false.
Extend 04704 with the nested-NULL shapes at depth 1 and 2, with Variant, and
with the mixed Tuple(Dynamic, UInt8) pair that distinguishes a position-wise fold
from one that short-circuits once NULLs pair up. Every previously committed cell
keeps its value. Also add the missing indexOfAssumeSorted oracle column.
… the type recursions A NULL nested inside a non-null Nullable(Tuple(...)) was lost. ColumnNullable::isNullAt reports on the wrapper, not on a NULL nested below it, so with both wrappers non-null the NULL-vs-NULL arm of the fold never fired; the wrapped tuple went to `equals` whole, which returns element-level NULL for a one-element tuple, and that was classified as no match. Membership therefore answered 0 where master answers 1, inside the contract this change already advertises for NULLs nested in Tuple. Strip the wrapper before decomposing, keep its null map, and fold it with the same rule the leaf fold applies: two NULLs match, a lone NULL does not. Dropping the null map instead would make a genuinely NULL tuple compare equal to a non-null one whose nested payload happens to hold the nested default, so the map is load-bearing and is covered by cells that pair a NULL wrapper against such a needle in has, indexOf and countEqual. Also add checkStackSize to hasTypeErasingElement and evaluateElementwiseEquality. Both recurse once per nested Tuple level and the depth is user-controlled through a CAST or DDL type string, bounded only by max_parser_depth. The Tuple recursion this code replaces at the top level was already guarded that way (FunctionComparison::executeImpl), as is getLeastSupertype, so this restores the surrounding convention rather than introducing one. LowCardinality(Tuple(...)) is not a sibling carrier: it cannot be constructed at all.
Consolidating the array-shaped dispatch into executeArray made the Map entry
point reach executeArrayLowCardinality for the first time. That arm assumes
index 0 of a LowCardinality dictionary is the NULL entry, which holds for the
plain array path but not for a Map: DataTypeMap::isValidKeyType rejects nullable
keys, so index 0 is the dictionary's default value. A NULL needle therefore
matched whichever key happened to sit at index 0, and
has(CAST(map('', 'v'), 'Map(LowCardinality(String), String)'), NULL) returned 1
where it had returned 0.
Restore the normalisation the Map path performed before executeArray existed.
A dedicated commit added it for exactly this reason in 72e311a
("Strip LowCardinality in has() Map path before nullable preprocessing"),
whose test 04338_has_map_dynamic_key_lowcardinality_arg still covers it; the
comment this replaces had that history inverted.
Every affected shape now matches the pre-change answer, and the plain
Array(LowCardinality(T)) path is untouched: the new test group pins the Map
answers against the array-path oracle and keeps a control row asserting the
array path's current answer, which is a separate question on a non-erased type.
Membership over an erased element type answered by variant identity rather than by value: has([1::UInt64]::Array(Dynamic), 1::UInt8) was 0 while the scalar comparison 1::UInt64::Dynamic = 1::UInt8 is 1. compareAt orders Dynamic and Variant by type name or discriminator before value, so equal values stored under different alternatives never compared equal. Replace an operand that resolves to one concrete alternative by that alternative and compare with the registered equals, which is the relation scalar = uses. This takes the two fast paths FunctionVariantAdaptor itself gates on, and declines everything else, so a column holding several alternatives at once, a shared-variant row, a container alternative, a LowCardinality element, and any pair equals rejects all keep their previous answer. Admissibility has to be decided by running equals rather than by inspecting types, because the comparison subsystem admits string pairs by type and then converts per value: '1'::String compares with 1::UInt8 while 'abc' does not. Nullness is folded outside equals, once per wrapper level, so an outer NULL stays distinguishable from one nested below it. Tuple recursion is unbounded because Tuple(Tuple(Dynamic)) is reachable, and stops at Array and Map, whose equality is compareAt-based too and therefore cannot change by being routed here. Heterogeneous and shared-variant columns keep master's pre-existing cross-type miss; that residue, along with hasAny, hasAll and arrayCompact, is out of scope here and tracked separately.
A block of rows shares one flattened ColumnArray data column, so asking the
peel whether the operand holds a single concrete alternative asked it about the
union of every row's elements: ColumnVariant reports a variant as non-empty for
the whole column, and getGlobalDiscriminatorOfOneNoneEmptyVariant returns
nothing as soon as a second one is non-empty. One heterogeneous row therefore
declined for every row in its block, including the single-alternative rows this
path exists to fix. The answer for a row became a function of which rows
happened to share its block, which varies with max_block_size, part layout,
PREWHERE and parallelism, and is not something a user can see or control.
FunctionArrayIndex does not override isDeterministic, so that is unsound for
constant folding, index analysis and the query cache regardless of whether a
consumer trips over it today.
The whole-block attempt is kept first, so a block that already resolves to one
alternative is unaffected and pays nothing. When it declines, the rows are
grouped by the one global discriminator all of that row's elements carry, and
each group is evaluated by the existing peel machinery: a group's sub-block is
single-alternative by construction. Rows whose own elements disagree, and groups
the peel still declines, are handed to the existing dispatch for exactly those
rows, so they keep the answer they had. Reaching that dispatch without
re-entering the erased path is why executeArray is split in two.
A per-position partition was measured and rejected: it needs master's answer for
an individual position, and every arm of the tail folds by ColumnArray::Offsets
and emits one value per row, so no per-position fallback exists short of
rebuilding the array with identity offsets.
Grouping is sound because a materialized equals verdict follows from the type
pair alone, not from the values: measured over four type pairs, a parseable and
an unparseable value give the same verdict (materialize('1') = 1::UInt8 and
materialize('abc') = 1::UInt8 are both NO_COMMON_TYPE). So a group's admit or
decline verdict is stable across its rows, and grouping cannot make one row's
answer depend on another's. This does not revive per-type grouping of a
heterogeneous comparison, which stays refused: heterogeneous groups are never
formed.
tryPeelErased also stops reconstructing the alternative with expand() over a
mask, which assumed the variant's offsets ascend with the superproject row
order. ColumnVariant::validateState only bounds-checks offsets, never their
order, so the reconstruction now builds an explicit selector from getOffsets()
and calls index(), removing the assumption instead of documenting it.
Measured against a pristine-master build: the same [1::UInt64] row with needle
1::UInt8 now answers 1 in a mixed block, at max_block_size = 1 and across two
parts, matching the answer it already got in a homogeneous block. Over 4000
rows in four classes, has/countEqual/indexOf sum to 3000/3000/4000 against an
independent oracle's 3000, where master gives 2000/2000/3000, and all four
block sizes agree on both builds. Heterogeneous rows, shared-variant rows,
container alternatives and LowCardinality elements keep master's answer.
findVariantAtPath returned a raw pointer aliasing a function-local ColumnPtr. The caller then read the pointee across a whole row loop, so the function was correct only under an unstated invariant: that no convertToFullColumnIfConst in the descent ever materialises a temporary. I could not reach that shape through SQL (ColumnTuple rejects a ColumnConst child, and the mainstream producers of a const-valued array convert before constructing), but a ColumnArray's own data column can hold one, which upstream documents in the ColumnArray constructor's NOTE, and closing it by reachability would need an audit nobody will repeat at the next refactor of this file. Pass the owning ColumnPtr back through an out-param instead, which is the convention unwrapNullable already uses a few functions earlier in the same file. Behaviour is unchanged: the traversal, the nullptr returns and every answer are the same, verified by the test and audit outputs being byte identical to the previous build's.
Internal second-model reviewBefore publishing I ran this change past an independent reviewer model and adjudicated every finding ❌ Blockers found and fixedNested Same defect one wrapper out, in Same defect in
Unbounded type recursion with no stack guard. Both new recursions descend once per nested A row's answer depended on which rows shared its block. The first design admitted a whole block
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260803-170600 |
|
cc @george-larionov @CurtizJ, could you review this? |
|
Workflow [PR], commit [2f045ea] Summary: ❌
AI ReviewSummaryThis PR routes Findings❌ Blockers
Final VerdictChanges requested. The row-group fallback is still incorrect for tuple operands with more than one erased leaf, on both the haystack and varying-needle sides. LLVM Coverage ReportMeasured on commit 2f045ea.
Changed lines: Changed C/C++ lines covered: 430/445 (96.63%) · Uncovered code |
Style check flagged two rules on arrayIndex.h, both introduced by this PR. various_checks.sh forbids a ContextPtr member under src/Functions: such a copy can outlive its context in deferred-execution paths (default expressions, async inserts, MergeTree), and every entry in its exception list is a function that genuinely needs a live context at execution time. This one does not - the context was only ever used to resolve `equals`. So resolve the overload resolver once in the constructor and keep that instead, as coalesce.cpp does for isNotNull/assumeNotNull/if/multiIf. A null context stays benign, because FunctionComparison::create falls back to default ComparisonParams. The removed comment claimed a resolver cannot be a member because one instance resolves one overload (IFunction.h:370) while Tuple leaves need one each. That warning targets resolvers whose IFunction has mutable fields, which the same comment names as the offender class. FunctionComparison holds only a const ComparisonParams and no mutable state, and IFunctionOverloadResolver::build derives everything from its arguments, so repeated builds on differing leaf types are safe. coalesce.cpp relies on exactly that, calling build in a loop with a different argument type each iteration. check_cpp.sh lint 08 wants memory-tracking containers under src/Functions, so std::vector and std::unordered_map become VectorWithMemoryTracking and UnorderedMapWithMemoryTracking. These allocate through a MemoryTracker that throws rather than overcommitting. Verified both directions: 04706 is byte-identical to its reference with this change and differs on 50 lines against pristine master, so the fix is preserved and the test still discriminates.
|
Pushed
I also removed a comment of mine that claimed a resolver cannot be a member, on the grounds that
Verified both directions: One thing worth flagging that this commit does not fix. CREATE TABLE t (a Array(Tuple(Dynamic, Dynamic))) ENGINE = Memory;
INSERT INTO t VALUES ([(1::UInt64, 2::UInt64)]);
SELECT has(a, (1::UInt8, 2::UInt8)) FROM t; -- 1
INSERT INTO t VALUES ([(1::UInt64, 'x')]);
SELECT has(a, (1::UInt8, 2::UInt8)) FROM t; -- 0 for both rowsI measured this identically before and after The remaining |
| const auto & elements = tuple_type->getElements(); | ||
| for (size_t position = 0; position < elements.size(); ++position) | ||
| { | ||
| if (auto nested = findErasedPath(*elements[position])) |
There was a problem hiding this comment.
findErasedPath stops at the first erased leaf it encounters, so the row-group fallback still treats Array(Tuple(Dynamic, Dynamic)) as homogeneous whenever only the first field agrees. A sibling row that differs only in the second erased field then sends the whole group back to the old compareAt path, and rows that are single-alternative in both tuple positions stay wrong.
Repro:
CREATE TABLE t (a Array(Tuple(Dynamic, Dynamic))) ENGINE = Memory;
INSERT INTO t VALUES ([(1::UInt64, 2::UInt64)]), ([(1::UInt64, 'x')]);
SELECT has(a, (1::UInt8, 2::UInt8)) FROM t ORDER BY tuple();The first row should still be 1, but this implementation falls back to the old answer for both rows because the grouping key ignores the second erased leaf. The fallback needs to key on all erased tuple positions, not just the first one.
The per-row-group fallback partitioned on the array side only. When the needle
is itself a materialized Dynamic or Variant whose alternative varies by row, a
group could still hold two different needle types, so the peel declined for the
whole group and every member fell back to compareAt. A row that peels cleanly
on its own then answered differently depending on which rows shared its block,
which is the property the change set out to establish:
CREATE TABLE t (id UInt8, v Array(Dynamic), n Dynamic) ENGINE = Memory;
INSERT INTO t VALUES (0, [1::UInt64], 1::UInt8), (1, [2::UInt64], 'x');
SELECT id, has(v, n) FROM t ORDER BY id;
Row 0 returned 0 in that block but 1 when read alone, while 1::UInt64 = 1::UInt8
is 1. Master answers 0 in both, so it was self-consistent and this was a
regression introduced by the row-group pass rather than a pre-existing gap.
The grouping key now carries both alternatives. Discriminator is a UInt8, so the
pair packs into a UInt16, and a needle that is not erased contributes a constant
half and leaves the partition as it was. Rows whose own elements disagree are
still ungrouped, and a group is only evaluated when every member peels the same
way on both sides.
The block-independence group of 04706 gained the needle-side shapes: the same
two rows under three block partitions, for has, indexOf and countEqual, with a
declared Variant needle as well. Without this change the mixed-block partitions
answer 0 where the one-row partition answers 1, so the new cells fail on the
previous commit and pass here; the rest of the test is byte-identical across
both.
The pair key admits 255 * 255 groups where a single discriminator admitted 255, and each group held an IColumn::Filter spanning the whole block, so the worst case grew with the square of the alternative count: at 65536 rows the bound went from about 16 MiB to about 4 GiB of filters. The rows now carry one group label each, the distinct labels present are collected, and a filter is materialised only for a group the block really holds. Nothing about the partition changes, so the answers are identical; peak RSS on a full 65536-row block with both sides widened is within 8 MiB of the previous commit and the query is faster, since the labels replace a scan per group.
The three partitions were asserted only against each other, and a comment promised a Tuple-nested needle that the schema did not build. The oracle for these rows cannot be an element-wise `x = n` in the same row: that asks for one common type across the whole column and throws NO_COMMON_TYPE, so it would assert nothing. Reading a row on its own is what "the answer is the row's own" means, so each shape now also reads each row alone, and that is the value the partitions have to reproduce. On the previous commit the shared-block partitions answer 0 where the single-row read answers 1, so the cells contradict each other there and agree here. The Tuple(Dynamic) needle the comment described is now actually constructed, which exercises the needle path by descent rather than at the top level. It reddens on the previous commit too.
The decline list covered the comparison subsystem rejecting a pair by type, but
not a pair it accepts by type and then cannot convert. equals reports that as
NOT_IMPLEMENTED, which propagated, so a query that used to answer now threw:
CREATE TABLE t (v Array(Variant(IPv4, Float64)), n Variant(IPv4, Float64))
ENGINE = Memory;
INSERT INTO t VALUES ([toIPv4('1.2.3.4')], toFloat64(5));
SELECT has(v, n) FROM t;
Master returns 0. A single row is enough, so this is the peel itself rather than
the grouping, and it reached every commit of the branch so far. The stated
contract is to decline for any pair equals rejects, so NOT_IMPLEMENTED joins the
list and the existing dispatch answers as before.
04706 gained that pair; it throws on the previous commit and returns 0 here.
Why one label per row rather than a filter per group belongs in the commit that made the change, not next to it.
|
Both findings are real. The second one is in this PR's contract and is now fixed here; the first is not, and is measured to be equally wrong on master. Needle-side mixed alternatives: fixed in
|
| shape | master | previous head ae4f8d9 |
now |
|---|---|---|---|
| row 0 in the mixed block | 0 | 0 | 1 |
| row 0 read alone | 0 | 1 | 1 |
So the previous head answered the same row differently depending on its blockmate, which is exactly the property the PR body claims. groupRowsByAlternative partitioned on the array side only, so a group could still hold two different needle types, the peel declined for the whole group, and every member fell back to compareAt.
The grouping key now carries both alternatives. ColumnVariant::Discriminator is a UInt8, so the pair packs into one key; a needle that is not erased contributes a constant half and leaves the partition as it was.
04706 gained the needle-side shapes under all three block partitions, for has, indexOf and countEqual, plus a declared Variant needle and a Tuple(Dynamic) needle. The oracle there is the row read on its own rather than an expression in the same row: an element-wise x = n over these rows asks for one common type across the column and throws NO_COMMON_TYPE, so it would assert nothing. On ae4f8d9 the shared-block partitions answer 0 where the single-row read answers 1, so the new cells contradict each other there and agree here.
Two things came out of reviewing that fix, both also in this push:
- The pair key admits far more groups than a single discriminator did, and each group held a filter spanning the whole block, so the worst case grew with the square of the alternative count. The rows now carry one group label each and a filter is built only for a group the block really holds. On a full 65536-row block with both sides widened this is 2.6x faster at equal peak RSS, median of three runs each.
- A peeled pair whose types have a supertype the comparison accepts but no conversion between them made the call throw where master answers.
has([toIPv4('1.2.3.4')]::Array(Variant(IPv4, Float64)), toFloat64(5)::Variant(IPv4, Float64))returned 0 on master and raisedNOT_IMPLEMENTEDon every commit of this branch so far;equalsreports that case with a code the decline list did not cover. One row is enough, so it was the peel rather than the grouping. Now declined, with that pair asserted in04706.
Multiple erased tuple leaves: out of this PR's contract
Reproduced verbatim, and it is a genuine defect, but it is not one this PR creates or is scoped to fix. A/B on the source file alone, each arm's Build ID verified to move:
| arm | row alone | with the sibling row |
|---|---|---|
| this branch | 1 | 0 |
| master | 0 | 0 |
Against master the shared-block case is unimproved, 0 to 0, not newly broken, so declining to widen findErasedPath here keeps the change at the scope its body describes. A fix task owns it, and the fixing-PR link will be posted here when it opens. It carries the repro, the findErasedPath / groupRowsByAlternative / evaluateElementwiseEquality trace, a composite-key sketch, and the coverage gap that all 29 existing tuple assertions are single-erased-leaf.
One warning for whoever picks that up: arrayMap(e -> e = <needle>, a) throws NO_COMMON_TYPE on a heterogeneous Array(Tuple(Dynamic, Dynamic)), and arrayExists(e -> isNotDistinctFrom(e, <needle>), a) returns 0 where direct = returns 1, so neither is authoritative for these types.
hasTypeErasingElement descended only through a bare Tuple, so an erased leaf below a Nullable(Tuple(...)) nested inside a Tuple was invisible to it and executeErasedEquality never ran for such a shape. The two helpers that walk the same structure, findErasedPath and findVariantAtPath, already decay a Nullable at each level, so the gate was the only place that did not, and the elementwise evaluator folds each wrapper level's nullness at its own level and can serve the shape once admitted. Measured on Array(Tuple(Nullable(Tuple(Dynamic)))), materialized, with the answer paired against scalar = on the same peeled pair: has/indexOf/countEqual answered 0/0/0 where = answers 1, both on pristine master and on this branch before this commit, and answer 1/1/1 after it. The same holds past a non-erased leading tuple element. The four single-wrapper control shapes are unchanged, and the rest of the test's 128 reference lines are byte-identical, which refutes the concern that relaxing this predicate would move committed cells. Reverting only the decay reddens exactly the two new cells and nothing else. Reported by the AI reviewer on the pull request.
The first version of these cells paired only has with scalar =, leaving the position and the count asserted against reference text alone. A single matching element also made both reduce to 1, which a constant would satisfy. The array now carries a non-matching leading element and the match twice, so indexOf is 2 and countEqual is 2, and each has a same-row oracle built from = over the peeled pair. Those oracles read 2 unchanged on pristine master and on this branch before the decay commit, where the functions themselves answer 0, so they are independent of the change they check. Reverting the decay collapses all three answers to 0 while all three oracles hold.
AI review round 2: the nested-
|
Array(Tuple(Nullable(Tuple(Dynamic)))) |
pristine master | branch before | branch now |
|---|---|---|---|
has |
0 | 0 | 1 |
indexOf / countEqual |
0 / 0 | 0 / 0 | 2 / 2 |
scalar = on the peeled pair (oracle) |
1 | 1 | 1 |
The asymmetry described is real: findErasedPath (arrayIndex.h:879) and findVariantAtPath
(:836-840) both decay a Nullable at each level, and hasTypeErasingElement was the only one of
the three that did not, so the gate rejected shapes the machinery below it can serve. Fixed in
a414df6a by the matching decay; the elementwise evaluator already folds each wrapper level's
nullness at its own level, so nothing else was needed. The same holds when the wrapper sits past a
non-erased leading tuple element.
The concern recorded earlier on this branch, that relaxing this predicate would move already-committed
cells, is refuted by measurement: the rest of the test's reference is byte-identical, and reverting
only the decay reddens exactly the new cells and nothing else.
Also acted on: the first version of those cells oracled only has, and a single matching element made
indexOf and countEqual both reduce to 1, which a constant would satisfy. 07166f4b gives the array
a non-matching leading element and the match twice, so the two reduce to 2, each with its own same-row
oracle. Those oracles read 2 on master and on the pre-fix branch, where the functions answer 0, so they
are independent of what they check.
Not fixed here, deliberately
The multi-erased-leaf case (Array(Tuple(Dynamic, Dynamic)), where a blockmate varying in the second
leaf flips another row's answer) is raised again this round. Re-measured at the current head: 1 alone
vs 0 with the sibling, against 0 / 0 on pristine master, so versus master it is unimproved rather than
newly broken, and it needs findErasedPath to enumerate every erased path plus composite-key grouping
whose cardinality is the product of per-leaf alternative counts. That performance envelope deserves its
own review rather than being folded in here. A fix task owns it, and the fixing-PR link will be posted
here when it opens.
The request to add an element-wise oracle to the block-partition cells cannot be met as prescribed: on
those fixtures the needle is itself a materialized erased column whose alternative varies by row, so
arrayExists(x -> x = n, v) throws Code: 386 NO_COMMON_TYPE and produces no output at all. The
working oracle for that shape is reading the row on its own and requiring every block partition to
reproduce it, which is what those cells already do.
Build IDs verified to move per arm and pinned against readelf -n; mutation restored to the same
Build ID. 04706 byte-identical to its committed reference, stderr empty.
Session id: cron:clickhouse-maint-slot-13:20260804-171931
CI finish ledger - 07166f4Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this PR. The diff is confined to Session id: cron:our-pr-ci-monitor:20260804-233000 |
Resolves the one conflict in src/Functions/array/FunctionsMapMiscellaneous.cpp. Both sides gave FunctionMapToArrayAdapter a context-taking constructor: this branch to thread a context into the Impl (so the erased-element equality path can resolve `equals` with the query's comparison settings), and master's 80b20d4 to read `enable_lazy_columns_replication`. The resolution keeps both initializers in declaration order. Master's change also generalized FunctionWithLowCardinalityFastPath: `create` now forwards a context when the base accepts one, and its default constructor is constrained with `requires std::is_default_constructible_v<Base>`. That supersedes the `FunctionMapToArrayAdapter() = default` this branch had added purely so the mixin could default-construct its base, so the defaulted constructor is dropped. Keeping it would have left master's new enable_lazy_columns_replication member uninitialized on that path.
…e plain groupRowsByAlternative required the array element type to have an erased path, so it declined whenever the elements were plain and only the needle was erased. executeErasedEquality routes such a pair through this machinery too, because the common type is Dynamic or Variant, so the whole-block attempt could decline on a needle column holding several alternatives and the call fell through to executeGeneric. That cast both sides to Dynamic and answered 0, which made a row whose own pair compares cleanly depend on which rows shared its block. Either side may now supply the grouping key, and a side that erases nothing contributes the same key half for every row. Measured on has/indexOf/countEqual over Array(UInt64) against a Dynamic needle: before, 4 of 7 rows answered differently depending on the block partition; after, each row has one answer across every partition, and the values agree with the same comparisons written over plain non-erased types.
|
Confirmed, and fixed in 2caa7a6. Your repro reproduces exactly as described. On the previous head, row Worth recording that master is not block-dependent here, it is uniformly wrong: it answers Scope of the defect, measured over 12 block partitions of a 7-row table (one block,
Every answer that changed matches the same comparison written over plain non-erased types,
One note on the shape of the fix: my first draft also declined when neither side was erased. The |
CI finish ledger for 2caa7a6No failures to own on this run. Run carries real coverage. GitHub: 177 checks, 160 success, 17 skipped, 0 failures. Praktika: The skips are all reasoned rather than dropped work: Session id: cron:our-pr-ci-monitor:20260814-150000 |
Master moved the same constructor seam in FunctionArrayIndex: create() now reads type_json_skip_null_typed_paths and hands it to a bool constructor, while this branch passes the context so the erased-equality path can build an `equals` resolver. Resolved by keeping a single context constructor that derives both - the resolver as before, and skip_null_typed_paths from the same context, guarded because a null context is already documented as benign here. The member gets an in-class initializer because this branch keeps a defaulted default constructor where master relied on the bool parameter's default argument. Master's changes to the other touched files are kept as-is: the stringFamilyPairIsNotEqualityEquivalent guard in ArrayExistsToHasPass, the float-zero needle guard and the JSON typed-path handling in arrayIndex.h.
`notHas` arrived on master while this branch was open. It builds the internal `has` resolver on every call, and on this branch that factory needs a context so the erased-element comparison can be resolved with the query's settings. The resolver is now built once in create(), the same way the `not` resolver already was, and held next to it.
executeErasedEqualityConstArray materialized the array for the batch it was about to process and handed that copy to the fallback when the row-group attempt declined. The fallback compares a constant array's elements as Fields and a materialized array's as columns, so a row answered differently depending on how many rows shared its block: with a 251-element mixed constant array and a UInt8 needle, has() answered 1 over 100 rows and 0 over 300. The batch now hands the fallback the constant array resized to the batch, which also drops the replicated copy. The test asserts that the two row counts agree, and pins notHas as the negation of has, which it now also is under type_json_skip_null_typed_paths since it resolves has through the context-aware factory.
Merged master at
|
…er's
`executeErasedEqualityPerRowGroup` asks the pre-existing dispatch for the rows its
grouping leaves undecided, and it materialized every argument before filtering it
down to those rows. For a constant array that changes the answer: the pre-existing
dispatch compares a constant array's elements as `Field`s and a materialized one's
as columns, and for a type-erasing element the two do not agree. A row's answer
therefore depended on which other rows shared its block.
CREATE TABLE t (id UInt8, n Dynamic(max_types = 1)) ENGINE = Memory;
INSERT INTO t VALUES (0, 2::UInt64), (1, 1::UInt8);
SELECT has([1::UInt64::Dynamic], n) FROM t WHERE id = 1; -- 1
SELECT id, has([1::UInt64::Dynamic], n) FROM t ORDER BY id; -- row 1 gave 0
`max_types = 1` leaves row 1's `UInt8` in the shared variant, so the grouping
decides row 0 and declines row 1. `n = 1::UInt64::Dynamic` is 1 for that row and
master answers 1 for both readings, so the two-row block was a regression this
branch introduced.
`ColumnConst::filter` already returns a `ColumnConst`, so dropping the
`convertToFullColumnIfConst` before the filter is the whole fix. The batched
constant-array arm then needs no special case of its own: it hands the grouping
the same constant instead of the flattened copy, which stays where it is used.
The mixed-alternative counts move with it. A needle whose alternative the
comparison cannot relate to the elements at all is declined, and a declined row
now keeps the existing dispatch's `Field`-based answer at every block size:
300/150/150, where this branch gave 150/150/0 above a block size of one and
300/150/150 at one. Master gives 300/150/150 throughout.
Co-Authored-By: Claude Opus 5 <[email protected]>
`hasContainer` walks bare `Tuple` wrappers only, so a container reached through a
`Nullable(Tuple(...))` wrapper is not held back by the barrier: `tryPeelErased` peels
the alternative, `evaluateElementwiseEquality` decomposes it, and `equals` decides the
leaf. The docstring said "any chain of Tuple wrappers", which reads as though the walk
saw through `Nullable` the way `hasTypeErasingElement` does.
The asymmetry is deliberate. A top-level `Nullable` alternative cannot occur at all,
since `DataTypeVariant` rejects `Nullable` and `LowCardinality(Nullable)`, so reaching
this shape needs an outer bare `Tuple` and `enable_nullable_tuple_type = 1`:
SET enable_nullable_tuple_type = 1;
CREATE TABLE t (v Array(Dynamic), n Dynamic) ENGINE = Memory;
INSERT INTO t SELECT [CAST(tuple(CAST(tuple([1::UInt64]), 'Nullable(Tuple(Array(UInt64)))')), 'Dynamic')],
CAST(tuple(CAST(tuple([1::UInt8]), 'Nullable(Tuple(Array(UInt8)))')), 'Dynamic');
SELECT has(v, n), arrayExists(x -> x = n, v) FROM t; -- 1, 1
For those rows `equals` answers 1 across element widths, and so does the constant-array
`Field` comparison, while the materialized `compareAt` path answers 0. Stopping at the
hidden container would therefore answer 0 for a materialized array and 1 for a constant
one, and would contradict `=` on the same pair in the same row.
Pins the shape in `04706` for `Array` and `Map` payloads over the materialized,
single-row and constant-array regimes, each paired with that oracle.
Co-Authored-By: Claude Opus 5 <[email protected]>
… them The cells pairing a constant array against varying needles, and the notHas cell sharing their carrier, built the array with arrayMap(x -> x::UInt64::Dynamic, range(...)). The old analyzer does not constant-fold a call taking a lambda, so under enable_analyzer = 0 the array arrived materialized (isConstant measured 0 there, 1 with the analyzer on) and the cells silently measured the materialized path instead of the constant one they name. The reference, written for the constant path, cannot hold for both. That failed 3 of 3 reruns on Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) at deeee9f: mixed needles gave 150 150 0 for 300 150 150, the batch-count cell 0 0 0 0 for 1 1 2 1, and notHas 0 1 for 1 0. CAST(range(0::UInt64, 1000::UInt64, N::UInt64) AS Array(Dynamic)) is the same value, keeps the elements' alternative at UInt64, and folds under both analyzers, so the constant path stays covered on the old analyzer instead of being pinned away from it. The reference is unchanged. The invariants the cells assert already held under the old analyzer: the three arms agreed with each other, the one-batch and several-batch counts agreed, and notHas stayed the negation of has. Only the path the cells reached differed.
CI finish ledger - 0a1e15bEvery 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
Same signature over the last 30 days: 35 rows on 32 distinct PRs, 0 on master. Of the 170 check runs at this head 151 succeeded, 18 were skipped as not applicable and 1 failed (the row above); Session id: cron:our-pr-ci-monitor:20260906-100111 |
Master's ClickHouse#117313 landed in the same file and for the same class of defect: it brought `has`/`indexOf`/`countEqual` closer to `equals` for native numbers (`accurate::equalsOp` replacing the hand-rolled comparisons) and for date/time types that count different units (`executeDifferentDateTimeUnits`, hooked at the top of `executeArrayImpl`). Both of its insertion points sit right where this branch adds its own erased-element dispatch, which is why the textual merge could not place them. Resolved as a union, with master's block kept where master put it: the date/time arm stays first after `allowArguments`, this branch's `executeArray` / `executeArrayAfterErasedEquality` / `tryGetDecayedCommonType` and the erased-equality machinery follow, and both new includes are kept. The two arms do not overlap: `dateTimeUnitOf` answers `NotDateTime` for an erased type, so master's arm declines on every shape this branch handles, and the undecided-row fallback still reaches it through `executeArrayAfterErasedEquality`.
…rased
`has`, `indexOf` and `countEqual` answered 0 for an erased needle over an
`Array(LowCardinality(T))` while `=` answers 1:
has(materialize(CAST(['a'], 'Array(LowCardinality(String))')), 'a'::Dynamic) -> 0
has(materialize(CAST(['V0'], 'Array(LowCardinality(String))')), toFixedString('V0', 3)::Dynamic) -> 0
with the `arrayExists` oracle answering 1 in both cases, and `indexOf` and `countEqual` agreeing
with `has` rather than with the oracle.
The erased-equality arm declined a LowCardinality element type and left those rows to the dictionary
path, which decides them by the bytes of the needle cast to the dictionary type. That is not the
comparison `=` performs: a `FixedString` needle casts to three bytes where the element holds two,
although the two meet as `String` where the padding is trimmed back off, and
`targetTypeRepresentsValue`, which guards that cast, asks for the meeting type as
`makeNullable(...)`, which an erased type cannot be inside, so it reports even a lossless cast as
having lost the value.
The reason the arm declined was that the dictionary path answered a NULL needle from dictionary slot
0 whether or not that slot is the null one, which equality has no equivalent for. Master has since
declined a NULL needle unless the dictionary can hold one (`fc180a05603c9`), so that answer now
agrees with `=`, and the arm no longer has anything to preserve by standing aside.
The other sign is unchanged, and is now pinned: no common type brings a number and a `String`
element together, so `equals` rejects that pair and
`has(materialize(CAST(['1'], 'Array(LowCardinality(String))')), 1::UInt64::Dynamic)` stays 0 instead
of answering from the needle's spelling as a string. A needle that erases nothing also keeps the
dictionary path, since the arm only takes a pair whose common type erases something.
Two expectations in `04706` move because master changed them, not this branch: after
`fc180a05603c9` a NULL needle no longer matches a dictionary's default slot, so the control cell and
the `mapContainsKey` cell agree with `=` as well.
`enable_analyzer = 1` is dropped from the two rewrite arms and the old analyzer is out of the
comments: the setting is obsolete since v26.9 and can no longer be turned off.
Merged master at
|
CI finish ledger - 02f33afEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260920-160237 |
|
|
||
| const ColumnVariant * needle_variant = nullptr; | ||
| ColumnPtr needle_holder; | ||
| if (auto needle_path = findErasedPath(*needle_type)) |
There was a problem hiding this comment.
groupRowsByAlternative still keys the needle side off only the first erased leaf it finds. For a needle like Tuple(Dynamic, Dynamic), two rows that agree on the first field's alternative but differ on the second are still put into one group, so evaluateElementwiseEquality declines on that whole group and every row in it falls back to the old compareAt path.
Repro:
CREATE TABLE t
(
id UInt8,
v Array(Tuple(UInt64, UInt64)),
n Tuple(Dynamic, Dynamic)
)
ENGINE = Memory;
INSERT INTO t VALUES
(0, [(1::UInt64, 2::UInt64)], (1::UInt8, 2::UInt8)),
(1, [(1::UInt64, 3::UInt64)], (1::UInt8, 'x'));
SELECT id, has(v, n) FROM t ORDER BY id;Row 0 should stay 1, but in the two-row block it is forced through the fallback because the grouping key ignores the second erased needle field. The grouping key needs to cover all erased tuple positions on the needle side, not only the first path returned by findErasedPath.
CI finish ledger - b0b255aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The red This head is @alexey-milovidov's master merge Session id: cron:our-pr-ci-monitor:20260921-000159 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
has,indexOf,indexOfAssumeSorted,countEqual,mapContainsKeyandmapContainsValuemissing rows that=matches when the array element type is type-erasing (DynamicorVariant, including nested inTuple):has(materialize([1::UInt64]::Array(Dynamic)), 1::UInt8)returned 0 while1::UInt64::Dynamic = 1::UInt8is 1. The fix applies to a row whose own elements resolve to one concrete alternative andequalsover that peeled pair succeeds; other rows keep the previous behaviour.notHasbuilds its internalhasthrough the same factory, so the two stay negations of one another, including undertype_json_skip_null_typed_paths. The needle side is covered too: an erased needle over anArray(LowCardinality(T))was decided by its bytes in the dictionary, not byequals.Description
Related: #112953
At default settings the functions above miss rows that scalar
=matches, andcountEqualbreaks thearrayCount(elem -> elem = x, arr)equivalence it documents.Root cause.
FunctionArrayIndexcompares withIColumn::compareAt(...) == 0, butColumnDynamic/ColumnVariantorder by variant name before value, so equal values under differentvariants never compare equal.
The change. One dispatcher at both array entry points covers all six instantiations, constant,
materialized and
LowCardinality. For a type-erasing common type it peels an operand resolving to oneconcrete alternative and compares with the registered
equals, folding each wrapper level's nullness atits own level;
Tuplerecursion stops atArray/Map.Scope, decided per row group, so a row's answer follows from its own elements and the needle, not
from which rows share its block, and a constant array's batches keep comparing the constant so batch
boundaries cannot move it either. It declines for rows mixing concrete types, shared-variant rows,
container alternatives reached through bare
Tuplewrappers and any pairequalsrejects; declined rows keep master's answer bit-for-bit.has([NULL], NULL)over amaterialized erased array now matches. No setting is added.
notHaslanded on master meanwhile. Its internalhasneeds the query context here, so it takes itfrom the same factory: under
type_json_skip_null_typed_paths = 1a NULL typed path giveshas0 andmaster's
notHas0 too, not the negation it documents; now 1.Validation.
04706pairs every cell with an oracle in the same row, pins each declined shape, andasserts block partitions and batch sizes agree. A/B against master over the 229 stateless tests reaching
these functions: identical failure sets; 50/50 OK.
Validation detail
#112953touches this file but neither entry point.Left for separate PRs, each measured unchanged on both arms in a run where
hasitself moved0 -> 1 on the same fixture:
hasAny/hasAll(separate GatherUtils implementation);arrayCompact;container equality itself (
[1::UInt64::Dynamic] = [1::UInt8::Dynamic]is 0 while theTupletwin is1, which is why this fix stops there); and the heterogeneous-row miss.
Mutations, each rebuilt with the Build ID confirmed to move, the whole test re-run, then restored
with it confirmed to return. Each reddens only what is named:
DynamiconlyVariantcellsMappathhas(map, key)TuplerecursionTuplecells; thenTuple(Tuple(Dynamic))NullableNullable(Tuple(Dynamic))cellsMapcardinality normalisationMapNULL-needle cellsLowCardinality-needle cellPerformance (debug,
max_threads=1): a materialized 200k x 50 array goes 0.287 s -> 0.135 s.A constant array is batched against the needles instead of expanded per row, so a 1000-element one over
200k rows holds master's peak: 289 -> 287 MB, 295 MB with mixed needle alternatives.
The updated reference (
04338, 2 lines) now enforces its own comment, "has(m, k)must agreewith
has(mapKeys(m), k)for every row":has(map(NULL::Dynamic, 1), CAST(NULL, 'LowCardinality(Nullable(String))'))was 0, the array path 1.Workflow [PR]
Sync PR [sync-upstream/pr/113208]