Repository navigation
Conversation
…e NULL Range-based pruning silently dropped rows when an Array, Map or Tuple value had a NULL element. The predicate orders two such values with IColumn::compareAt, in which a NULL element sorts after every value, and the part data is stored in that order. KeyCondition's range arithmetic orders them with accurateLess, whose FieldVisitorAccurateLess has no container branch, so Array < Array falls through to Field::operator<, which compares the type tag first with Field::Types::Null at tag 0 and therefore sorts a nested Null before every value. A range drawn from such values does not bound what the predicate compares. PartsSplitter.cpp:42-47 already states this divergence in a TODO and already declines its own optimization for these types through isSafePrimaryDataKeyType. A NULL at the top level is different: index and key analysis represent it with a POSITIVE_INFINITY sentinel (ColumnNullable::getExtremesNullLast, promoted back on read in MergeTreeIndexMinMax), so those orders agree. Both the sentinel selection and the promotion are top-level-only, which is why only nested Nulls are affected. After the RPN is built, any atom reading such a key column is reset to FUNCTION_UNKNOWN. That is the RPN's neutral element and is documented as always relaxed, so isRelaxed, alwaysUnknownOrTrue, PartitionPruner::useless, trivial-count exactness and the force_index_by_date usefulness check all stay correct with no further change, and atoms on the other columns of a composite key or index keep pruning. KeyCondition.cpp already leaves an atom FUNCTION_UNKNOWN for a Nullable key for the same class of reason. One seam covers every carrier measured wrong on master: the minmax skip index, the part-level minmax index over a partition key expression, the partition pruner, count() by a partition predicate, primary-key mark pruning (where the row that disappears is an ordinary non-NULL one), and the set skip index on the non-bulk path reached with secondary_indices_enable_bulk_filtering = 0. Under the default bulk path the set index never consults the hyperrectangle at all, so it is unaffected either way. The cost is that such a key or index stops pruning even when no NULL is present. Recovering it needs a minmax index format version able to serialize an out-of-band bound so the decision can be made per granule; aligning the two orders instead, which the PartsSplitter TODO asks for, moves the whole accurateEquals / accurateLess / accurateLessOrEqual family across src/, including the has, indexOf and countEqual semantics that Functions/array/arrayIndex.h builds on accurateEquals. Object and JSON nested in a container are not covered: canContainNull does not include them, they need a non-default allow_minmax_index_for_json, and no measurement was taken. IDataType::hasDynamicSubcolumns() is not usable to detect them because DataTypeMap::hasDynamicSubcolumnsData() returns true unconditionally and would declare every Map(String, String) offending. The Variant and Dynamic legs are covered by the delegation to hasTypeThatCanContainNulls but are untested because a key expression over those types is refused with DATA_TYPE_CANNOT_BE_USED_IN_KEY.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex) plus my own cold review of the
| 7 | ❌ | The new type guard admits float containers, so a nested Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20260827-062000 |
|
Workflow [PR], commit [cdcbd0a] Summary: ❌
AI ReviewSummaryThis PR declines key and index range analysis for container-typed keys whose elements can be Findings
Tests
Final VerdictChanges requested until the null-check atoms on LLVM Coverage ReportMeasured on commit cdcbd0a.
Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session ids: cron:clickhouse-impl-self-slot-57:20260827-002800 (gate answers), |
|
cc @hanfei1991 @al13n321, could you review this? A |
03733_has_function_key_condition_explain asserted that a has() IN-set atom over a Tuple(Nullable(UInt32), Nullable(UInt32)) sorting key prunes to 2 of 100 granules. That key type is declined here, so the arm now reads 100/100. Its results-only sibling 03733_has_function_key_condition is unchanged, which is what shows the decline only over-reads. That arm's own query is answered correctly without the decline, but the property that makes it correct belongs to the consumer, not to the atom, so it is not available where the RPN is built. A primary-key mark range is [index[i], index[i+1]) over first-row values in storage order, and MergeTreeSetIndex sorts its ordered_set and compares against those bounds with IColumn::compareAt, so an IN-set atom there is ordered consistently. Range atoms on the same key are not: with a nested NULL on a granule boundary the mark range is inverted under Field order, and k = (5, 1), k > (5, 1) and k >= (5, 1) AND k <= (5, 2) each lose a row. A minmax bound is not a compareAt envelope at all, because ColumnArray::getExtremes picks the pair under opposite nan_direction_hints, and there an IN-set atom is wrong too: (u, a) IN ((2, [NULL])) over a composite minmax index drops its only matching row, which is what the comp_in arm of 05045 pins. Exempting IN-set atoms would reintroduce that.
… array path 03464_projections_with_subcolumns asserted that a projection whose sorting key is `json.c[].d.:Int64` is used for pruning. That key is `Array(Nullable(Int64))`, so the range arithmetic orders a nested NULL first while the data and the predicate order it last, and the pruning it asserted is unsound. Measured on unmodified master, with an array element whose `d` path is absent: `json.c[].d.:Int64 > [6]` returns [7,8] where the correct answer is [7,8,9]. The reference is regenerated for the three p3 sites; the p1, p2 and t.a assertions are byte-identical. This carrier was missed until CI hit it for two reasons worth recording. The offending type is derived from the key expression, so no column declares it and no grep for the type name can find the table. And a projection sorting key is not gated by `allow_nullable_key`, unlike a table sorting key, so a sweep that assumes that setting is required excludes the whole projection surface. A new arm in 05045_pruning_container_null_element pins the wrong result.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units8 translation units recompiled, 20 s compile time in total, 8 of them have a recent master baseline. |
The three plan assertions regenerated here read the base table, so the WHERE survives as a step, and whether it renders as `Expression` or `Filter` depends on the condition being moved to PREWHERE. `optimize_move_to_prewhere` and `query_plan_optimize_prewhere` are randomized independently at 5% each and either one off renders `Filter`, so the test failed about 6% of runs: 3 of 50 locally, every failure carrying only the three `Expression` to `Filter` lines seen in CI, and both settings drawn False across those three. With the pin, 0 of 50. Note the `long` tag divides the repetition count by ten, so a 50-run flaky check gives this test 5 runs. `03733_has_function_key_condition_explain` asserts `Filter` at 14 sites and needs no pin: its queries read only the filtered column, so PREWHERE has nothing to defer and the node does not change. Verified with each setting forced off.
|
|
||
| for (auto & element : rpn) | ||
| { | ||
| if (std::ranges::any_of(element.key_columns, [&](size_t position) { return unusable_columns.contains(position); })) |
There was a problem hiding this comment.
unsetAtomsOnColumnsWithoutUsableRange now rewrites every atom that touches one of these keys to FUNCTION_UNKNOWN, but the helper right above already calls out that a top-level NULL is still ordered consistently through the existing +Inf sentinel. extractAtomFromTree still builds bare FUNCTION_IS_NULL / FUNCTION_IS_NOT_NULL atoms for that path, and key IS NOT DISTINCT FROM NULL reuses the same atom.
That means a key like Nullable(Tuple(Nullable(String))) now loses primary-key / minmax pruning for WHERE isNull(key) and WHERE key IS NOT DISTINCT FROM NULL, even though those predicates never depend on the nested-element ordering bug this PR is fixing. Please exempt the null-check atoms from this blanket rewrite and add a focused regression arm for that case.
CI finish ledger - cdcbd0aCI is fully finished at this commit. One check failed, and it has an owner.
Everything else at this commit is green: 177 praktika nodes, 152 Session id: cron:our-pr-ci-monitor:20260827-180000 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results when a
minmaxskip index, aPARTITION BYexpression or a sorting key is built over a container column whose elements can beNULL, such asArray(Nullable(String)),Map(String, Nullable(String))orTuple(Nullable(String)). Matching rows were silently dropped, including rows that contain noNULLthemselves.Description
Related: #107074, #116455 (no open issue).
The predicate orders container values with
IColumn::compareAt, where aNULLelement sorts last, andthe data is stored that way.
KeyCondition's range arithmetic usesaccurateLess, whose container armfalls through to
Field::operator<, which compares the type tag first, so a nestedNullsorts first andthe range bounds nothing.
I decline the atom: after the RPN is built, an atom reading such a key column becomes the neutral
FUNCTION_UNKNOWN, documented always relaxed, soisRelaxed,alwaysUnknownOrTrueand trivial-countexactness stay correct while other key columns keep pruning.
KeyCondition.cppalready does this for aNullablekey. One seam fixes all seven carriers:minmaxskip index, part-level minmax, partitionpruner,
count()by a partition predicate, primary-key marks, thesetindex without bulk filtering,and a projection sorting key.
The projection carrier hides: no column declares it.
json.c[].d.:Int64isArray(Nullable(Int64)), and a projection sorting key is not gated byallow_nullable_key. On master,with one array element missing that path,
json.c[].d.:Int64 > [6]returns[7,8]where the answer is[7,8,9], so03464_projections_with_subcolumnswas asserting unsound pruning and its reference isregenerated.
Cost: such a key stops pruning even with no
NULLpresent, soforce_primary_keythere now raisesINDEX_NOT_USED, and03733_has_function_key_condition_explain's reference is regenerated. Itsresults-only sibling is unchanged: declining only over-reads. Recovering it needs a minmax
format version with an out-of-band bound, or aligning the two orders across
accurateLess.Variant/Dynamickeys are refused withCode: 549.Workflow [PR]
Sync PR [sync-upstream/pr/116655]