Repository navigation
Return 0 or 1 from isNull - #119785
Return 0 or 1 from isNull#119785
Conversation
A Nullable null map byte only has to be non-zero to mean NULL:
ColumnNullable::isNullAt is `byte != 0`, and the Native format spec states
that senders may write any non-zero byte. `if` forwards its raw condition
column into the null map sink, so `if(number % 3, NULL, 'x')` produces a map
holding 0, 1 and 2, and SerializationNullable round-trips it through MergeTree
verbatim.
isNull returned that byte, from two places:
* FunctionIsNull::executeImpl returned the embedded null map column by
pointer, so the stored bytes became the UInt8 result and any consumer that
treats it as a number read 2 as two.
* The optimize_functions_to_subcolumns rewrite (on by default) replaced
isNull(x) with a bare x.null column read, so on a MergeTree column the
function was not evaluated at all. Its two sibling arms in the same table
already wrap the subcolumn in a function that collapses any non-zero byte:
count(x) becomes sum(not(x.null)) and isNotNull(x) becomes not(x.null).
That asymmetry is why isNotNull and count measured correct.
The compiled path already canonicalized (CreateICmpNE(byte, 0) plus
CreateSelect), so one query over one dataset answered differently depending
only on compile_expressions: sum(isNull(e) + 0) over 30 rows, 20 of them NULL,
returned 30 interpreted and 20 compiled.
Both paths now return 0 or 1, and the rewrite wraps the subcolumn like its
siblings. not(not(x.null)) rather than notEquals(x.null, 0), which was the
first shape tried: ConditionSelectivityEstimator::extractAtomFromTree
recognises a bare <col>.null reference and treats it as IS NULL, and RPNBuilder
handles `not` structurally, so a `not` chain still reaches that handler while a
comparison node does not. With the comparison shape, PREWHERE ordering by
null-count statistics silently stopped working: on a table where `a` is 100%
NULL and `b` 50%, the prewhere filter went from and(b.null, a.null) to
and(notEquals(a.null, 0), notEquals(b.null, 0)), putting the least selective
condition first, which 04266_statistics_basic_prewhere asserts against. The
`not` shape keeps that estimate and keeps the narrow read: 226 compressed bytes
and 2 file opens for sum(isNull(e)) over 30k rows, unchanged.
The x.null subcolumn deliberately still exposes the stored byte. It is a
physically stored stream, and a skip index, projection or sorting key can be
built over it from non-canonical bytes; canonicalizing the read then loses rows
against that metadata (measured: INDEX idx e.null TYPE minmax over all-byte-2
data with WHERE e.null = 1 prunes to Granules: 0/1, and ORDER BY e.null prunes
Granules: 0/8, which MATERIALIZE INDEX cannot repair for a primary index). Its
documented 1/0 wording is corrected to the format spec's own domain instead.
Normalizing at the producer was rejected for the reason ClickHouse#119729 recorded: the
output is valid per the spec, and it cannot repair a part already on disk or a
Native block from a peer.
A persisted artifact an older server computed at write time from isNull(...)
over such a column holds a value this fix no longer produces. Measured with two
binaries over one data directory, index_granularity 4, all-byte-2 data: a
sorting key and a skip index prune to Granules: 0/8 and are repaired by
OPTIMIZE TABLE ... FINAL and ALTER TABLE ... MATERIALIZE INDEX; a partition key
keeps its stored value 2 across a merge and needs a rewrite into a fresh table;
an aggregate projection keeps its stale state through both MATERIALIZE
PROJECTION and OPTIMIZE FINAL and needs CLEAR PROJECTION followed by
MATERIALIZE PROJECTION. A sorting key that composes a non-monotone function
over isNull stops being sorted by its own key expression, so OPTIMIZE FINAL
raises LOGICAL_ERROR "Sort order of blocks violated" and the remedy is a full
rewrite. Every such schema is already answering wrongly before this change: a
nullness partition key holding byte 2 already yields three partitions where two
were asked for.
Related: ClickHouse#119633
Related: ClickHouse#119729
Co-Authored-By: Claude Opus 5 <[email protected]>
classifySparsityPredicate answers SELECT count() FROM t WHERE n IS NULL from the per-column num_defaults recorded in serialization.json, without reading the column. It matches on the predicate's shape and accepted a .null subcolumn only as the predicate root or as the direct argument of one `not`, which covered a bare x.null read and the isNotNull rewrite. Wrapping isNull in a second `not` put the predicate outside every accepted shape, so the classifier declined and the read fell back to a full null-map scan. That was a live regression, not a latent one: 04279_sparsity_persist_exact_num_defaults asserts exactly those three plan lines and does not pin optimize_functions_to_subcolumns, which tests/clickhouse-test randomizes, so it would have failed about half the time. Accept one nested `not` over a null map, classified as MatchesDefault. num_defaults is itself truthiness-based (ColumnNullable::isDefaultAt is isNullAt), so it already counts a byte 2 as one NULL and the optimization answers correctly on a non-canonical map once it is recognised again: over 5000 rows with a map of 0, 1 and 2 bytes, the scan baseline and the optimized count both return 3333. The scope is deliberately one nested `not` over a null map, not an arbitrary `not` chain and not a nested `not` over a truthy integer column: no rewrite produces those shapes. 05212 gains the plan-level coverage whose absence let this through. It pins the classifier at both values of optimize_functions_to_subcolumns, pins that the optimized count agrees with a scan on a non-canonical map, and pins that skip index analysis still reaches the subcolumn through both `not`s (force_data_skipping_indices would raise INDEX_NOT_USED otherwise). Its JIT-versus-interpreter pair also gains a control shape holding no isNull, compared through ProfileEvents['CompiledFunctionExecute'] as 05170_jit_cast_nullable_to_non_nullable does, because a pair that only compares two result values is silently vacuous wherever compilation does not happen. Related: ClickHouse#119633 Related: ClickHouse#119729 Co-Authored-By: Claude Opus 5 <[email protected]>
Three of the test's rows assert behaviour that exists only on the analyzer code
path, so the file fails deterministically in the stateless jobs that run with
allow_experimental_analyzer=0 (ci/defs/job_configs.py selects them, and
tests/config/install.sh --analyzer installs users.d/analyzer.xml):
* optimize_functions_to_subcolumns is read only in
FunctionToSubcolumnsPass.cpp and there is no old-analyzer rewriter, so under
the old analyzer the setting is a no-op. The row that forces the e.null skip
index on isNull(e) then reads e, the index is unusable, and the query raises
INDEX_NOT_USED. Being an exception, it also aborts the rest of the file.
* classifySparsityPredicate is called only from PlannerJoinTree.cpp, the
analyzer's planner, so the two rows looking for "Optimized trivial count
with sparsity filter" in EXPLAIN return 0 instead of 1, at both values of
the setting.
Both were measured against this binary with a client-level enable_analyzer=0,
which is what the job's profile setting does server-side.
04279_sparsity_persist_exact_num_defaults carries the same tag for the same
mechanism. The tag sits after the `-- { echo }` line because the tag parser
scans every line, and it is mirrored into the reference because echo mode
prints comment lines, as 03636_storage_alias_basic does.
Related: ClickHouse#119633
Co-Authored-By: Claude Opus 5 <[email protected]>
The comment claimed that index analysis sees through `not` but not through a comparison with 0. The second half is false, and 05212 refutes it directly: forcing the e.null skip index on `WHERE e.null = 1` returns rows without raising INDEX_NOT_USED, so index analysis handles a comparison on the subcolumn perfectly well. The recognisers that really require a bare `.null` reference under `not` are the null-count statistics estimator, whose atom handler is keyed on a bare subcolumn reference, and SparsityFilter's column-reference matcher, which accepts only a physical storage column. Those are what the shape choice is constrained by, so those are what the comment now names. Comment only. Stripping comments from both revisions with the preprocessor leaves byte-identical output, and the linked binary is unchanged. Co-Authored-By: Claude Opus 5 <[email protected]>
The echoed label still claimed that isNull(n_alias) rewrites to n.null, which this change makes false. Its LIKE '%n.null%' assertion is unaffected and still passes, so only the stated claim was stale. Three documentation sites carrying the same claim are corrected earlier in this change; this is the fourth. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review (4 rounds, the last one clean; click to expand)An independent model reviewed each revision, plus my own cold review of the resulting code. Fixed here. ❌ The rewrite put Disagreed, ❌ versioned compatibility for persisted keys. The consequence is real and stays Disagreed, 💡 the synthesized |
|
Workflow [PR], commit [990aba5] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict✅ No new findings from this review. LLVM Coverage ReportMeasured on commit 990aba5.
Changed lines: Changed C/C++ lines covered: 73/83 (87.95%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units13 translation units recompiled, 35 s compile time in total, 13 of them have a recent master baseline. |
CI finish ledger - d798002Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260913-173109 |
| - For other values, the `IS NULL` operator always returns `0`. | ||
|
|
||
| Can be optimized by enabling the [optimize_functions_to_subcolumns](/reference/settings/session-settings/optimize#optimize_functions_to_subcolumns) setting. With `optimize_functions_to_subcolumns = 1` the function reads only [null](/reference/data-types/nullable#finding-null) subcolumn instead of reading and processing the whole column data. The query `SELECT n IS NULL FROM table` transforms to `SELECT n.null FROM TABLE`. | ||
| Can be optimized by enabling the [optimize_functions_to_subcolumns](/reference/settings/session-settings/optimize#optimize_functions_to_subcolumns) setting. With `optimize_functions_to_subcolumns = 1` the function reads only [null](/reference/data-types/nullable#finding-null) subcolumn instead of reading and processing the whole column data. The query `SELECT n IS NULL FROM table` transforms to `SELECT not(not(n.null)) FROM TABLE`. |
There was a problem hiding this comment.
This seems excessive and unnecessary. This looks like a problem in the consumers, not a problem we need to fix in every producer.
There was a problem hiding this comment.
You are right, I will drop the not(not(...)) and fix it at the read.
The raw byte reaches a query from two places: FunctionIsNull::executeImpl, which returns the embedded mask by pointer (src/Functions/isNull.cpp:78), and the .null subcolumn read, which I deliberately left raw here. Canonicalizing the second one makes the analyzer change, the SparsityFilter shape and both docs edits unnecessary, because isNull(x) -> x.null is then already correct as it stands.
It also removes an inconsistency I measured today rather than inferred. Same data (5000 rows of if(number % 3, NULL, 'x')), same type, two serializations: Sparse gives DISTINCT e.null = [0,1] and sum(e.null) = 3333; Default gives [0,1,2] and 4999, against countIf(e IS NULL) = 3333 on both. The sparse path canonicalizes because it rebuilds the map from the offsets (SerializationSparse::NullMapSubcolumnCreator::create, SerializationSparse.cpp:248), while the dense path hands the stream straight through (SerializationNullable.cpp:52-59). Doing the same for the dense null-map substream is one place, and it puts .null back on the 1/0 its own docs promise.
The one cost: a skip index, key or projection built over e.null itself by an older server keeps the raw bytes, so it joins the upgrade list already in the description for isNull(...) carriers. I will fold that into the same entry.
Reworking it that way. If by consumers you meant a different place, tell me and I will go there instead.
There was a problem hiding this comment.
Please don't. I'll push a simplified change
There was a problem hiding this comment.
Holding off, nothing further from me on this branch unless you ask for it.
One measured thing, since it argues your way: the applyNullMapImpl change repairs a lost value, not just a wrong isNull byte. if(cond, x, NULL) with a Nullable x hands the raw condition to applyNegatedNullMap (if.cpp:1274), so 1 ^ 2 was 3 and the row came back NULL with its condition true.
SELECT if(materialize(toUInt8(2)), CAST('x', 'Nullable(String)'), NULL) AS v, isNull(v);
master 46715b2 -> \N 3 ('x' is correct)
this branch -> \N 1 canonical byte, value still lost
My isNull change was hiding that case rather than fixing it.
I updated the description to match your commit and put that case in the changelog entry. Tell me if you want anything else from me here.
Algunenano
left a comment
There was a problem hiding this comment.
This change seems really overdone it. We should fix it in the consumers, not add not() calls everywhere
Algunenano
left a comment
There was a problem hiding this comment.
I've done some changes to use col.null != 0 instead of not(not(col.null)) which avoids an additional function call and adjusted the selectivity estimator to support this condition too. Also fixed some places that assumed the null byte was always 1 when enabled (vs anything not 0).
The fixture built its non-canonical null map with `if(number % 3, NULL, 'x')`, relying on `FunctionIf::executeForNullThenElse` forwarding the raw condition column as the result's null map (src/Functions/if.cpp). That producer is reached only while the result type is a plain `Nullable(T)`: a constant value branch leaves the result type divertible to `LowCardinality(...)`, and since `FunctionIf` does not override `useDefaultImplementationForLowCardinalityColumns()` the framework then wraps the result, routing nullness through a dictionary index (src/Columns/ColumnUnique.h) so the map that reaches storage is canonical 0/1. The test's fixture-validity guard measures the byte distribution directly (`WHERE e.null = 1` counts only the 10 rows whose byte is exactly 1, not all 20 NULL rows), so any such typing choice flips it from 10 to 20 and reddens the test on unrelated work. PR ClickHouse#80263, which types `if` with constant branches as `LowCardinality` under a new setting and registers that setting in the randomisation pool, made this happen on two legs, 88/88 and 157/157 runs with the drawn settings versus 153/153 and 173/173 without. Materializing the value branches makes `isColumnConst` false on them, so no constant-branch typing rule can apply, while the executed path on master is unchanged: `convertToFullColumnIfConst` becomes a no-op and the raw condition column is still forwarded. No expected value changes; the results-only projection of the reference differs by exactly the one row added by the new control, which measures the canonicalisation a `LowCardinality` result causes and reads `30 20 20` where the unwrapped shape reads `30 10 20`. The guard is kept: it is the only assertion in the file that detects whether the fixture still carries a non-canonical map. Related: ClickHouse#119785
…ull-map-byte-is-a-predicate Conflicts in `ColumnNullable.cpp`, `ColumnVariant.cpp` and `ColumnsCommon.cpp`, all resolved to master's side. Master now reads those null maps as predicates itself: both `applyNullMapImpl` negations were fixed in 990aba5 (ClickHouse#119785), and `countBytesInFilterWithNull` was rewritten with a predicate-correct vector path and scalar tail (ClickHouse#119555 and the follow-up rework), so this branch no longer changes those three sites or their comments. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #119633
Related: #119729
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
isNullandIS NULLnow return1for everyNULLrow, including when the column's NULL mask holds a byte other than0or1, which the Native format permits and whichifproduces from its condition column. Previously such a row could contribute its raw byte, sosum(isNull(e))returned30where20is correct.if(cond, x, NULL)with aNullablexno longer returnsNULLfor a row whose condition byte was neither0nor1. If an older server stored a value computed fromisNull(...)of such a column (sorting key, skip index, partition key, projection,MATERIALIZEDorDEFAULTcolumn), rebuild it.Description
A
NullableNULL mask byte only has to be non-zero to mean NULL (Native format spec), andifforwards its raw condition column into the mask sink, soif(number % 3, NULL, 'x')stores the bytes 0, 1 and 2, and MergeTree keeps them.isNullexposed that byte twice:FunctionIsNull::executeImplreturned the embedded mask column, andoptimize_functions_to_subcolumns(on by default) replacedisNull(x)with a barex.nullread, bypassing the function.The compiled path already canonicalized, so one query gave two answers:
Both paths now return
0or1: the function canonicalizes, and the analyzer rewrite becomesx.null != 0, with the consumers that see through it taught that shape (990aba5): the trivial-count recogniser (SparsityFilter.cpp) and the NULL-count statistics behind PREWHERE ordering (ConditionSelectivityEstimator.cpp).Applying a NULL map is a consumer too.
if(cond, x, NULL)with aNullablexhands the raw condition toapplyNegatedNullMap(if.cpp:1274), where1 ^ 2gave3, so the row came back NULL although its condition was true:if(materialize(toUInt8(2)), CAST('x', 'Nullable(String)'), NULL)yields\Non master andxhere;ColumnVarianthad the same shape.x.nullstill exposes the stored byte on purpose, because canonicalizing a stored stream loses rows against metadata built over it (aminmaxindex overe.nullthen prunes every granule); its documented1/0wording is corrected instead.Upgrade: a value an older server computed from
isNull(...)and stored (sorting key, skip index, partition key, projection,MATERIALIZEDor calculatedDEFAULT) keeps bytes this fix no longer produces, so a query over it can lose rows. The remedy differs per carrier, and one has none.Measured carriers and the remedy for each
Pre-fix binary writes, post-fix binary reads the same data directory; 30 rows, mask byte 2; the query is
count() WHERE isNull(e) < 2unless a row names another; each remedy measured on its own clone.isNull(...)ORDER BY isNull(e)OPTIMIZE TABLE ... FINALORDER BY transform(isNull(e), [0, 1, 2], [1, 0, 2])OPTIMIZE FINALfails, because the part is no longer sorted by its own keyINDEX idx isNull(e) TYPE minmaxMATERIALIZE INDEX idxPARTITION BY isNull(e)OPTIMIZE FINALkeeps the partition named2PROJECTIONoverisNull(e), aggregate or normalsum60; a key-prunedcount()20CLEAR PROJECTIONthenMATERIALIZE PROJECTION;MATERIALIZE PROJECTIONalone repairs neither kindm UInt8 MATERIALIZED isNull(e)sum(m)60MATERIALIZE COLUMN md UInt8 DEFAULT isNull(e), omitted by the insertsum(d)60CLEAR COLUMN d, thenMATERIALIZE COLUMN d;MATERIALIZE COLUMNalone is a no-op on an ordinary columnMATERIALIZEDcolumn that is the sorting keysum(m)60MATERIALIZE COLUMNis refused withCANNOT_UPDATE_COLUMNThe projection rows need
optimize_functions_to_subcolumns = 0to diverge; the rest diverge at default settings.Workflow [PR]
Sync PR [sync-upstream/pr/119785]