Repository navigation
Conversation
The Native format defines a null map as a predicate: 0x00 means the value is
present and any non-zero byte, canonically 0x01, means NULL
(docs/reference/interfaces/specs/NativeFormat.mdx, Nullable). SerializationNullable
reads that stream back verbatim with SerializationNumber<UInt8>, so a null map of
2s and 4s is valid data that can arrive from a client, a replica or a distributed
sender, and can already be sitting in a part. ColumnNullable::isNullAt implements
the rule as bytes[n] != 0.
Eighteen readers instead treated that byte as a value: they hashed it, embedded
it in a key, scanned for the literal 1, or did raw arithmetic on it. FunctionIf
forwards its raw condition column to the null-map sinks, so if(number % 3, NULL,
'x') produces the bytes 0, 1 and 2, where byte 0 marks the rows holding 'x' and
both 1 and 2 mark rows that are equally NULL. Measured on numbers(30), and
surviving a MergeTree write and read back:
- DISTINCT and GROUP BY over one Nullable(String) key return 3 rows where 2 is
correct, because the 128-bit serialized key embeds the raw byte and the set
compares no values at all;
- when the map contains no byte 1 at all, if(toUInt8((number % 3) * 2), NULL,
'x'), a scan for that literal byte declares the block NULL-free and the whole
NULL group silently disappears, both for a string key and for a fixed-size
key whose bitmap tags only bytes equal to 1;
- countIf(isNull(if(number % 3, toNullable('x'), NULL))) returns 20 instead of
10, because applyNullMapImpl computes negative ^ map[i], and 1 ^ 2 is truthy,
so a row that holds a value becomes NULL; ColumnVariant::applyNullMapImpl
drops a present variant the same way once two variants are non-empty, which
is what takes it past its own single-variant fast path;
- max over a block in which every row is NULL returns the empty string instead
of NULL for if(toUInt8((number % 3) * 2 + 2), NULL, 'x'), whose map holds no
byte 0 and no byte 1: the Null combinator scans for a literal 1, finds none,
sets its has-a-value flag, and the nested aggregate's never-updated state is
emitted;
- dictGetKeys over a DIRECT layout, which reads its source rows on demand and
passes them through as stored, returns 20 keys where 10 is correct, so a NULL
attribute matched a value;
- an Iceberg INSERT records null_value_counts of 60 for a 30-row data file
holding 20 NULLs, because the manifest statistics add the byte values instead
of counting the non-zero ones, and a manifest that reports more NULLs than
the file has rows is invalid metadata that other engines read.
Make every reader agree with isNullAt. The sites group into raw arithmetic on the
byte (ColumnNullable and ColumnVariant applyNullMapImpl, and the Iceberg manifest
null counter), row identity (updateHashWithValue, serializeValueIntoArena,
serializeValueIntoMemory and the two IColumnHelper packed-key writers), scans for
the literal byte 1 (ColumnsHashingImpl block scan and createBitmap, the Null
aggregate combinator, hasOnlyTypeDefaults, basic statistics) and bitwise "present"
expressions (countBytesInFilterWithNull scalar tail, multiIf, accurate-or-null
tuple conversion, and both FunctionDictGetKeys paths, which now delegate to the
existing FilterDescription::preprocessFilterColumn instead of open-coding the
mask). In every bitwise expression both operands are reduced to predicates: a
bitwise complement of a truthy byte such as 2 leaves bit 0 clear, so masking
against it would read a NULL row as present.
On canonical 0/1 data every changed site is bit-identical, each being a != 0 on a
byte already in a register, and the replacement buffer scans read the same memory
as the memchr and memoryIsByte calls they replace. On such data no existing hash,
arena key, packed key, dedup token, stored part or query result moves, so no
setting and no SettingsChangesHistory entry is involved.
One compatibility window remains, on malformed maps only. An arena key is also an
aggregation-state key, and those bytes cross server versions by design
(IColumn::SerializationSettings::createForAggregationState): the Distinct
combinator, the generic groupArray, groupUniqArray and topK, and
groupArrayIntersect serialize, persist and merge them as raw bytes. A state
written by an older server therefore keeps its raw byte, so merging it with a new
state can still report two NULL keys for one logical NULL, and
groupArrayIntersect, which intersects by exact key, can drop such an element. I
add no state versioning for this: both encodings deserialize to NULL, no two
logically distinct keys can collide because a NULL row serializes to the null-map
byte alone, and preserving the old byte inside the state would leave these
aggregates wrong on a fully upgraded cluster. Canonical 0/1 states are
bit-identical and unaffected.
src/Functions/if.cpp is deliberately left alone. Its output is valid per the
format spec, the condition alias is a real zero-copy saving, and normalizing the
producer could repair neither a part already on disk nor a Native block from a
peer; it is also the only SQL-reachable generator of such a map, which is what
makes every face above reachable from SQL without a gtest.
Three comments asserted premises this change falsifies, so they are corrected
rather than deleted. On ColumnsHashingImpl, the cached null-map pointer was
documented as one where "each element is 0/1", which is exactly what justified
searching for a single 0x01, and the per-block flag was documented as the result of
a memchr that this change replaces with memoryIsZero. The NOTE on
countBytesInFilterWithNull said "the condition > 0 (to signed bytes) is used" and
that using "!= 0 ... does not allow SSE2", while toBits64 tests each byte for
equality with zero, so the vectorized path was itself an != 0 test and choosing
!= 0 for the tail costs no SSE2, for every byte value with the sign bit included.
The test pins compile_expressions and ratio_of_defaults_for_sparse_serialization,
both randomized in CI and both able to restore a canonical map before the reader
sees it: a JIT-compiled conditional stores CreateSelect(is_null, 1, 0) as its null
map, and a sparse map is rebuilt from its offsets as literal 1 and 0 bytes on read.
Measured against the unfixed binary, the first silences the five-argument multiIf
case and the second silences both cases that read from a part.
Not fixed here: isNull and the .null subcolumn still return the embedded byte,
so sum(isNull(e)) reports 30 where 20 is correct and SELECT e.null yields
{0, 1, 2} against a documented 1 or 0. That surface spans the function, its JIT
path, the optimize_functions_to_subcolumns rewrite and the subcolumn
serialization boundary; none of it is a key encoder, and fixing any part alone
would be a half-fix, so it is left as one separate change.
ColumnNullable::updateHashFast and updateHashWithValueRange also hash the raw
bytes, and stay as they are on purpose: their callers are identity and cache keys,
a query-tree constant hash, a prepared-set cache key and an INSERT deduplication
token, where a differing hash only recomputes or skips a deduplication and can
never change a result.
Closes: ClickHouse#119633
Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model plus a cold reviewer pass on each round (engine: codex;
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260913-030007 |
Pre-PR validation gate (click to expand)
Validation beyond the gate: 50/50 runs of the new test with settings randomization asserted live (1200 of 1299 queries carried the randomized bundle at 60-103 settings each and 51 distinct Session id: cron:clickhouse-impl-slot-6:20260912-235300 |
|
Workflow [PR], commit [1fd0e1e] Summary: ❌
AI ReviewSummaryThe PR makes Findings❌ Blockers
Tests
No local build or ClickHouse binary was available, so these upgrade cases were assessed from the current code and prior reported measurements rather than executed locally. Final Verdict❌ Block. Preserve insert retry identities through upgrades and reconcile old/new aggregate keys before merging, with focused regression coverage for both contracts. |
The header claimed that every reader must agree with isNullAt and treat 1
and 2 alike. isNull and the .null subcolumn are readers and still return
the raw byte: on a stored map of 0, 1 and 2, sum(isNull(e)) is 30 where 20
is correct and e.null yields 0, 1, 2. No query in this file observes that,
because every assertion here goes through a nullness test rather than the
byte value, so the comment now states that scope instead of a contract
this change does not deliver.
The .reference carries the same two lines because the test runs under
-- { echo }.
…n-canonical master 0bbfed8 ("Compute the remainder in a signed type when either operand is signed", ClickHouse#119616) landed between this branch's two CI runs and makes `number % -1` evaluate to 0 for every row: the remainder is now taken in a signed type, so the Int8 -1 no longer reaches the operation as 255 through the UInt8 result type. The report's own condition then selects the else branch for all 150 rows, the projection is a non-NULL constant, and the query answers 1 1 where the reference recorded 2 2 on the older base. Fast test fails on exactly that line on fe88b9e, the merge of this branch with master c08d0d8; the same query answers 2 2 on 4da0600, a merge from before ClickHouse#119616. An all-zero null map also leaves the query vacuous: with no non-canonical byte in the map it can no longer tell a nullness-based reader from a byte-based one. `number % 3` keeps the bytes 0, 1 and 2 there, matching the rest of the file, and its value does not depend on the mixed-sign rule that changed, so the query reads the same on both sides of ClickHouse#119616. Measured on three arms: the unfixed 4da0600 returns 3 distinct rows against 2 from GROUP BY, the disagreement the report describes, while fe88b9e and this branch's own base both return 2 2. The test passes 50/50 on fe88b9e.
The reported query reaches the raw-condition-as-null-map shape only after MultiIfToIfPass turns its three-argument `multiIf` into `if`. `multiIf`'s own path copies the selected branch instead and leaves a canonical 0/1 map, so with the rewrite disabled the query answers 2 2 on unfixed code as well and stops covering the regression without ever failing. tests/clickhouse-test randomizes `optimize_multiif_to_if` and picks 0 about once in twenty runs. Measured on an unfixed binary: with the rewrite on, DISTINCT returns 3 against 2 from GROUP BY and the null map holds the bytes 0, 1 and 2; with it off, both counts are 2 and the map holds only 0 and 1. The file's other faces build their maps through `if` directly and are unaffected either way. The limit itself is verified in both directions, since an unparsed line would just be a comment: across 60 randomized runs no query ran with `optimize_multiif_to_if = 0`, and 48 queries did as soon as the limit was removed.
`ColumnNullable::updateHashWithValue` is the one changed reader with no face in this test: DISTINCT and GROUP BY reach a Nullable key through the arena and the key-holder paths instead. A hash-only aggregate keeps nothing but the hash, so a raw byte hashed there cannot be normalized afterwards, which makes the missing coverage worth closing. The argument has to be a tuple, because a Nullable argument's NULLs are dropped by the aggregate's Null combinator before anything is hashed. Measured on a map holding the bytes 0, 1 and 2: the unfixed binary answers 3 and the fixed one 2, while the canonical control answers 2 on both.
…at all `uniqExact(tuple(x))`: the old analyzer removes the tuple as an injective wrapper before types are resolved, so the Null combinator drops the NULL rows again and both a fixed and an unfixed server answer 1. That is issue ClickHouse#114784, covered by 04927; this file only needs the wrapper kept, so the elimination is pinned off. `optimize_injective_functions_inside_uniq` is randomized as well, at 0 about once in twenty runs. The five-argument `multiIf`: only its columnar path reads the condition's null map. `allow_execute_multiif_columnar = 0` diverts the same query to the row-wise fallback, which tests truthiness already, and the expected output then holds on an unfixed server too. Measured there: 11/22/33 counts of 20/8/2 with the columnar path against the correct 10/17/3 from the fallback. Both pins are query-local, so nothing else in the file changes: the test passes 40 of 40 randomized runs and also under `enable_analyzer = 0`, where it failed before the first pin.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units509 translation units recompiled, 5183 s compile time in total, 509 of them have a recent master baseline. |
…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]>
| /// First serialize the NULL map byte. | ||
| auto * pos = arena.allocContinue(1, begin); | ||
| *pos = arr[n]; | ||
| *pos = arr[n] != 0; |
There was a problem hiding this comment.
serializeValueIntoArena is also the key format for aggregate states via IColumn::SerializationSettings::createForAggregationState() (AggregateFunctionDistinctMultipleGenericData, GroupArrayNodeGeneral, TopK, groupArrayIntersect, and the generic key-holder helpers). Canonicalizing arr[n] here changes that cross-version state format from raw 0x02/0x04 bytes to 0x01 without any version bump or dual-read/write path.
deserializeAndInsertFromArena still preserves the old raw byte, so after an upgrade an old state and a new state can carry the same logical NULL under two different serialized keys. Exact-key merges will then keep both keys distinct (or fail to match them in groupArrayIntersect) even though both deserialize to NULL. This needs explicit aggregate-state versioning / dual-format merge logic, or the aggregation-state serialization path has to keep the old byte encoding.
There was a problem hiding this comment.
I would suggest in ColumnNullable::deserializeAndInsertFromArena (ColumnNullable.cpp:245), change getNullMapData().push_back(val); to getNullMapData().push_back(val != 0);, and add a changelog note that saved aggregate states containing non-canonical NULL bytes are not repaired.
There was a problem hiding this comment.
Done in 35d1e77: deserializeAndInsertFromArena now pushes val != 0, and the changelog entry says saved aggregate states containing non-canonical NULL bytes are not repaired. A new case in 05210 finalizes an old-format groupUniqArray(Tuple(Nullable(String))) state whose NULL key byte is 2: the element's .null is 2 on master and 1 here.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…ull-map-byte-is-a-predicate Conflict in `IColumn.cpp`: master made `batchSerializeValueIntoMemoryWithNull` serialize a sub-range of rows (`start_row`, ClickHouse#124955); kept that shape and the canonical `is_null[row] != 0` key byte. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master now rejects `UInt64` columns on `CREATE` of an Iceberg table (ClickHouse#118596), so the test failed before reaching the null-map statistics. The key type does not matter to what it checks. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test builds the inner value with `if(number % 5, NULL, number)`, so the null map of rows 1 and 2 holds the bytes 1 and 2. The hash join keyed on the raw byte and matched each of those rows only with itself: 6 rows. With the null map read as a predicate both rows are the same `(NULL)` key and all four pairs match: 8 rows, the count that `CROSS JOIN ... WHERE l.k <=> r.k` and `join_algorithm = 'full_sorting_merge'` already return on master. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 327441dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261015-200013 |
|
Dear @SmitaRKulkarni, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
@groeneai : In src/Functions/if.cpp:1241, replace arg_cond.column in ColumnNullable::create(materializeColumnIfConst(result_column), arg_cond.column) with a 0/1 copy of the condition (map[i] = cond_col->getData()[i] != 0), so if stops writing the raw condition bytes as the null map. |
Review on ClickHouse#119729 asked for both, so the two places that produce a null map from a raw byte now write 0 or 1: - `FunctionIf::executeForNullThenElse` used the condition column itself as the result's null map, so `if(number % 3, NULL, 'x')` wrote the bytes 0, 1 and 2. It now builds a 0/1 copy of the condition, like the negated branch below it already does. - `ColumnNullable::deserializeAndInsertFromArena` pushed the key byte back verbatim, so a state written by an older server could put byte 2 into a result column. Such states are still not repaired: merging one with a new state compares the serialized keys, which this does not touch. The tests took their non-canonical maps from `if`, which no longer produces them, while existing parts and Native input still can. They now load such maps through `format(Native, ...)`, with the same bytes and rows the `if` expressions produced, so every data line of their references is unchanged. That includes `05212_isnull_non_canonical_null_map`, whose fixture relied on `if` forwarding byte 2. Two cases are new in 05210: the bytes `if` writes, and an old `groupUniqArray(Tuple(Nullable(String)))` state holding the key byte 2. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`05224_null_safe_join_fixed_keys` and the `if null map` cases of `05318_array_has_all_has_any_long_integer_arrays` also took their bytes 1 and 2 from `if`, which now writes 0 and 1, so the readers they cover would no longer see such a byte. Both now build the same keys and arrays from `format(Native, ...)`, and their references are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done in 35d1e77: The regression tests took their non-canonical maps from One side effect: an |
| auto null_map = ColumnUInt8::create(input_rows_count); | ||
| auto & null_map_data = null_map->getData(); | ||
| for (size_t i = 0; i < input_rows_count; ++i) | ||
| null_map_data[i] = cond_data[i] != 0; |
There was a problem hiding this comment.
❌ [P1] Preserve insert retry IDs when canonicalizing if output
This changes the data hash of an identical INSERT SELECT across an upgrade. For example, SELECT if(toUInt8(number % 3), NULL, materialize('x')) FROM numbers(3) ORDER BY ALL SETTINGS max_threads = 1, compile_expressions = 0 produces null-map bytes containing 0,1,2 before this change and 0,1,1 afterwards. ColumnNullable::updateHashWithValueRange still hashes the map verbatim, and DeduplicationInfo::calculateDataHashes uses that overload for the persisted block ID. Therefore, with deduplication enabled and a retained deduplication window, retrying the same insert after upgrading (or through another version during a rolling upgrade) inserts the block again. This affects ordinary SQL input and requires no non-canonical Native payload.
The latest discussion acknowledges this side effect, but there is no compatibility setting or migration here. Please gate the producer change so existing installations can retain their insert identities through the deduplication window, or provide a migration that recognizes the previous IDs. Add a focused cross-version retry regression; the new assertion that if emits only 0/1 does not cover this contract.
There was a problem hiding this comment.
Not changing this: canonicalizing if is the assignee's request (#119729 (comment)), and I measured that it inserts the block once more only when an identical INSERT SELECT whose if condition holds bytes other than 0 and 1 is retried across the version change inside the deduplication window. Gating it behind a setting is the reviewer's call.
…ull-map-byte-is-a-predicate # Conflicts: # src/Storages/ObjectStorage/DataLakes/Iceberg/DataFileStatistics.cpp
Master gained two key encoders that read a `Nullable` null-map byte as a value, and both must agree with the rest of this PR: - `HashedJoinKey::buildRows` (ClickHouse#129328) copies the bytes that `hash128` hashes, and its own contract is that every way of building a key gives exactly `hash128`. This PR makes `ColumnNullable::updateHashWithValue` hash `byte != 0`, so after the merge the copied raw byte broke that contract: on the merged tree `SELECT count() FROM t l JOIN t r ON l.s <=> r.s` over a Native null map with bytes 0, 1 and 2 aborts on the debug check in `buildRange` (AVX2 and NEON builds). It now copies `byte != 0`: 500 rows, where master gives 300. - `encodeFixedSizeKeys` (ClickHouse#124907) packs NULL into a one-bit field, so a byte 2 set the lowest bit of the column before it. With `transform_null_in = 1` and a set spilled to disk, `(0, NULL)` was found in `{(1, 0)}`: master 10 rows, 0 in memory. The right side is read back from the canonical in-memory keys, so only the probe side carried the raw byte. Both are bit-identical on 0/1 maps. 05210 covers both cases, and gains a `groupUniqArray(tuple(s))` case for the arena key encoder (`serializeValueIntoArena`), which no case reached: reverting it left 05210 green, now it gives 3 keys where 2 are correct. 05210 also pins `optimize_if_transform_const_strings_to_lowcardinality` to 0: the runner randomizes it since ClickHouse#80263, and with it `if` returns `LowCardinality(Nullable(String))`, which has no `.null` subcolumn, so the `if` case failed with UNKNOWN_IDENTIFIER on half the runs. 05211 is removed: ClickHouse#129812 made the Iceberg null count use `countBytesInFilter`, so that reader is master's now and the merge drops it from this PR (05211 passes on master). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes wrong results when a
Nullablecolumn's null map contains bytes other than 0 and 1, which the Native format explicitly permits.DISTINCT,GROUP BY,JOINandINtreated different non-zero null-map bytes as differentNULLkeys, and aGROUP BYkey could silently lose its entireNULLgroup. Saved aggregate states containing non-canonicalNULLbytes are not repaired. Closes #119633.Description
Closes: #119633
Per
docs/resources/develop-contribute/native-protocol/format.mdxthe null map is a predicate, one byte per row:0x00present, non-zero (canonically0x01) NULL.SerializationNullablereads it back verbatim, so such a map is valid input;isNullAtimplementsbytes[n] != 0.Sixteen readers instead treated it as a value: hashed, packed into a key, compared with
1, complemented. On 26.8ifforwards its raw condition column as the null map (bytes 0, 1 and 2; 1 and 2 are equally NULL), soSELECT DISTINCT if(number % 3, NULL, 'x') FROM numbers(30)returns 3 rows where 2 is correct. Also after a MergeTree round trip:DISTINCTandGROUP BYreturn two NULL rows (the report);1in the map, a scan for that byte calls the block NULL-free and the whole NULL group disappears;2or more,maxreturns an empty string instead of NULL.A hash
JOINmatched(NULL)keys with bytes 1 and 2 only to themselves (6 rows whereCROSS JOINgives 8), and a spilledINset found(0, NULL)in{(1, 0)}.Every changed site agrees with
isNullAt: seven key encoders, five literal-byte checks, four bitwise "present" expressions, bit-identical on canonical data. Master fixed four more (#119785, #119555, #129812).ifand aggregation-state reads now write only 0 and 1;if(cond, NULL, x)now copies its condition, asif(cond, x, NULL)always did. Existing parts and Native input can still carry other bytes (the tests useformat(Native, ...))..nulland the insert-deduplication hash still see the raw byte.An older server's state keeps its other
NULLkey bytes: merged with a new state, thatNULLappears twice (uniqExact(tuple(x))) orgroupArrayIntersectdrops it. I add no state versioning.Found by the AST fuzzer + correctness oracles fleet (#99980),
complete52-m0911, DISTINCT-via-GROUP-BY oracle, 2026-09-12.Workflow [PR]
Sync PR [sync-upstream/pr/119729]