Skip to content

Treat a Nullable null-map byte as a predicate, not a value - #119729

Open
groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/nullable-null-map-byte-is-a-predicate
Open

groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/nullable-null-map-byte-is-a-predicate

Conversation

@groeneai

@groeneai groeneai commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixes wrong results when a Nullable column's null map contains bytes other than 0 and 1, which the Native format explicitly permits. DISTINCT, GROUP BY, JOIN and IN treated different non-zero null-map bytes as different NULL keys, and a GROUP BY key could silently lose its entire NULL group. Saved aggregate states containing non-canonical NULL bytes are not repaired. Closes #119633.

Description

Closes: #119633

Per docs/resources/develop-contribute/native-protocol/format.mdx the null map is a predicate, one byte per row: 0x00 present, non-zero (canonically 0x01) NULL. SerializationNullable reads it back verbatim, so such a map is valid input; isNullAt implements bytes[n] != 0.

Sixteen readers instead treated it as a value: hashed, packed into a key, compared with 1, complemented. On 26.8 if forwards its raw condition column as the null map (bytes 0, 1 and 2; 1 and 2 are equally NULL), so SELECT DISTINCT if(number % 3, NULL, 'x') FROM numbers(30) returns 3 rows where 2 is correct. Also after a MergeTree round trip:

  • DISTINCT and GROUP BY return two NULL rows (the report);
  • with no byte 1 in the map, a scan for that byte calls the block NULL-free and the whole NULL group disappears;
  • when every byte is 2 or more, max returns an empty string instead of NULL.

A hash JOIN matched (NULL) keys with bytes 1 and 2 only to themselves (6 rows where CROSS JOIN gives 8), and a spilled IN set 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). if and aggregation-state reads now write only 0 and 1; if(cond, NULL, x) now copies its condition, as if(cond, x, NULL) always did. Existing parts and Native input can still carry other bytes (the tests use format(Native, ...)). .null and the insert-deduplication hash still see the raw byte.

An older server's state keeps its other NULL key bytes: merged with a new state, that NULL appears twice (uniqExact(tuple(x))) or groupArrayIntersect drops 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]

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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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;
29 findings over six rounds; the final round returned zero findings from the independent model and
none from the cold pass that required a change to the code).

# Sev Finding Verdict Evidence / action
1 ⚠️ No test distinguishes the aggregate all-NULL flag (AggregateFunctionNull.h:452); every shipped case uses an aggregate whose result is not Nullable, so it never enters the changed branch AGREE, fixed probed an all-NULL block with no byte 1 on both binaries; case added
2 ⚠️ ColumnVariant::applyNullMapImpl was justified as "correct in both directions", but that measurement exercises the fast path at :1826-1863 (one non-empty variant, no NULLs), which already tests truthiness, not the changed general branch at :1881 AGREE, fixed re-measured the general branch (two non-empty variants), where 2 ^ 1 = 3 drops a present value; case added
3 ⚠️ No test distinguishes the tuple accurateCastOrNull wrapper (FunctionsConversion.cpp:1170), where result & ~source turned a tuple holding a NULL element into a NULL tuple AGREE, fixed probed with a type-changing cast, since an identity cast self-cancels (map & ~map); case added
4 ⚠️ The two dictGetKeys sites have no case AGREE, fixed a DIRECT layout carries the stored map through and returned 20 keys where 10 is correct; case added. The vector path ships with a record: its row-level hash prefilter drops a byte-2 NULL row before the mask is consulted
5 ⚠️ ColumnsHashingImpl.h:387-391 still asserted that null-map bytes are 0/1 and that a memchr sets the fast-path flag, eight lines above the corrected sibling AGREE, fixed both comments rewritten to the predicate rule and to the scan actually present
6 💡 ColumnsCommon.cpp:71-74 claims a > 0 signed-byte comparison and that != 0 "does not allow SSE2" AGREE, fixed toBits64 is ~movemask(_mm_cmpeq_epi8(x, 0)), an equality test, so both paths are already != 0, sign bit included
7 ⚠️ sumNonNullStringBytes's String branch ignores the null map, so basic statistics count bytes under NULL rows DISAGREE true, but a different invariant: that branch never reads a null-map byte, and it over-counts identically under a canonical 0/1 map, so this change neither creates nor masks it. Fixing it means summing per-row lengths from the offsets, and it moves a size estimate, not a query result. Noted, not carried here
8 ⚠️ countBytesInFilterWithNull needs a case DISAGREE seven SQL shapes were measured on the pristine binary, all already correct, including countIf(<nullable>, <cond>) and block-boundary sizes over numbers(300) and numbers(63). A case there could not redden
9 ⚠️ ColumnNullable::hasOnlyTypeDefaults is left unexercised DISAGREE its only engine caller is gated by skip_empty_columns_on_insert, which defaults to false (MergeTreeSettings.cpp:213); even enabled, an all-NULL column becomes eligible for the missing-column marker and reads back as all NULL, so no result changes
10 💡 Comments and prose should spell a function reference as if, not if() AGREE, fixed raised twice; my first-round DISAGREE was wrong. AGENTS.md:13 (a symlink to the tracked .claude/CLAUDE.md) states the rule for documentation, comments and commit messages. Corrected in the test comment, the commit message and the description; application spellings such as if(number % 3, NULL, 'x') are left alone
11 ⚠️ Randomized expression JIT can canonicalize the null map before a case reaches the reader it tests: compile_expressions and min_count_to_compile_expression are both randomized, and a compiled conditional writes the null map as select(is_null, 1, 0) AGREE, fixed confirmed at IR level (compileFunction.cpp:188-190) and by compilability (FunctionMultiIf is a FunctionIfBase, and the five-argument case is all-native, so its JIT path bypasses calculateInserts). Measured on the unfixed binary, only the multiIf case is actually masked: the other two candidates have a Nullable(Nothing) branch, so their producer is never compiled and they stay red. Pinned with a per-setting random-settings clamp, then verified by showing the pristine binary goes green under the masking setting and that the clamped value is what the run actually uses
12 ⚠️ Randomized sparse serialization rewrites the two stored null maps as canonical, so both persistence cases pass with the fix reverted AGREE, fixed chooseKindStack selects sparse once the default ratio exceeds the randomized threshold (the tables sit at 20/30), and SerializationSparse rebuilds the map from offsets as literal 1/0 bytes. Pinned in the same clamp line; a 50/50 run cannot detect this class, because masking preserves the reference and the run stays green
13 💡 The changelog entry opened in the past tense AGREE, fixed docs/changelog_entry_guidelines.md:48 requires the present tense; the entry now opens "Fixes wrong results when ..."
14 💡 Comment-to-code ratio in the src diff Measured, no action Re-measured on the final tree, since round 5 added a hunk: 18 added comment lines against 24 added code lines, a ratio of 0.75, against 14 comment lines removed, so the net is +4. Earlier rounds reported 22 against 19 by counting added lines such as *pos = arr[n] != 0; as comment continuations. The longest added block is 2 lines, and each survivor states why a non-obvious domain property holds rather than narrating the fix. No comment was deleted to hit a ratio
15 ⚠️ The test header and the description both said number % 3 yields "bytes 0, 1 and 2 for rows that are all equally NULL", which contradicts the rule this change establishes: byte 0 marks a PRESENT row. The same comment also called a five-argument multiIf "four arguments" AGREE, fixed byte 0 carries the 'x' rows, so only the 1s and the 2s are equally NULL; corrected in the test comment, the reference, the description and the commit message. Arity counted directly: the call takes five arguments, and MultiIfToIfPass rewrites only the three-argument form (MultiIfToIfPass.cpp:41), which is what keeps this case on the columnar path
16 ❌ Canonicalizing the null byte in serializeValueIntoArena also changes an aggregation-state key. Those bytes are an explicitly cross-version format (IColumn::SerializationSettings::createForAggregationState, IColumn.h:342-347) that -Distinct, the generic groupArray/groupUniqArray/topK and groupArrayIntersect serialize, persist and merge as raw bytes, so an old 0x02 key and a new 0x01 key stay distinct although both deserialize to NULL AGREE on the fact, re-graded to ⚠️; disclosed, not versioned Verified: KeyHolderHelpers.h:25-29 serializes with those settings, AggregateFunctionDistinct.h:70-82 writes the raw keys into the state and merges them without re-encoding, and ColumnNullable::deserializeAndInsertFromArena (:240-251) pushes the raw byte back, so both keys read as NULL. By reading, groupArrayIntersect intersects by exact key, so it can drop such an element instead of duplicating it. Not versioned, because the affected inputs are exactly the malformed maps this change exists to fix, both encodings mean NULL, and preserving the old byte in the state would keep those aggregates wrong on a fully upgraded cluster: the honest trade is stated in the description and the commit message rather than decided silently. Canonical 0/1 data is bit-identical, so no ordinary state moves
17 💡 The rewritten block-scan comment in ColumnsHashingImpl.h asserts max_block_size = 65505, while DEFAULT_BLOCK_SIZE is 65409 (Defines.h:33-34, used by Settings.cpp:166); the surrounding clause is also performance motivation rather than a local invariant AGREE, fixed 65505 is an older release's value, inherited from the comment being replaced. The motivation clause is dropped and the invariant sentence kept, per the in-tree preference for keeping motivation in the commit message
18 💡 Same defect class one column over: CheckConstraintsTransform.cpp:105 decides "is violated" with !memoryIsByte(res_data, 0, size, 1), and the only type gate above it is isUInt8, so a CHECK yielding a truthy byte other than 1 would be reported violated Noted, not raised that column is a constraint result, not a null map, so it is outside this change's invariant, and I did not run it. Recorded here rather than turned into a claim or a follow-up
19 ❌ An eighteenth reader, missed by four rounds: DataFileStatistics::update accumulates the raw byte (null_counts[i] += v), so an Iceberg INSERT publishes null_value_counts of 60 for a 30-row file holding 20 NULLs AGREE, fixed verified end to end: the value reaches the manifest at IcebergWrites.cpp:604-605 beside record_count, on INSERT, on mutations (Mutations.cpp:333) and on compaction (Compaction.cpp:395), and 04652_iceberg_insert_per_file_statistics.sh already asserts that no entry may report more NULLs than its file has rows. Counting non-zero bytes instead, with a new IcebergLocal manifest-statistics case measured on both binaries. The tally in the description and the commit message moves to eighteen
20 ⚠️ The commit message said toBits64's equality test means "the vectorized path already agreed with the tail", which contradicts this change's own account of the defect: the pre-fix tail (*pos & ~*pos2) != 0 counted a null-map byte 2 as present and the vectorized path did not, which is why it hid in the last fewer-than-64 rows AGREE, fixed reworded to what is true and to what the removed NOTE actually got wrong: the vectorized path was itself an != 0 test, so choosing != 0 for the tail costs no SSE2, sign bit included
21 💡 "Make every reader agree with isNullAt" reads as exhaustive, but ColumnNullable::updateHashFast and updateHashWithValueRange still hash the raw bytes and were not named as exclusions AGREE, fixed their only callers are identity and cache keys (a query-tree constant hash, a prepared-set cache key, an INSERT deduplication token), where a differing hash recomputes or skips a deduplication and cannot change a result. Now stated in the commit message instead of left implicit
22 💡 The identical stale NOTE survives on countBytesInFilter (ColumnsCommon.cpp:36-39), and its declaration says it counts bytes "greater than zero" (ColumnsCommon.h:57) although the implementation is != 0 Noted, not carried that function reads no null map, so it carries none of this change's invariant, and correcting comments in an untouched function widens the diff for no behavioural gain. It did decide the shape of the fix in row 19: that call site spells the predicate out rather than leaning on a helper whose documentation contradicts it
23 ⚠️ Reviewer hypothesis, raised and then refuted: ORDER BY on a DISTINCT can answer from compareAt, which is nullness-based, so the two cases that sort the DISTINCT directly looked as though they could pass with the fix reverted DISAGREE, measured the plan shape does allow it (Planner.cpp:2943-3013 ends in a final DistinctStep, and applyOrder.cpp:66-76 gives it a sort prefix while optimize_distinct_in_order is on), but the full-file run on the unfixed binary shows the tuple case emitting its extra (NULL) anyway, so it reddens as written at the default value. The setting is randomized only between 0 and 1, and 0 disables that path outright, so no CI configuration masks it. The fixed-size-key case was never exposed: its defect drops the NULL group, and no deduplication can add a row back
24 ⚠️ The pre-PR validation comment claimed "exactly one changed site ships without a case", and still described a single new stateless test after round 5 added a second one AGREE, fixed measured against the tree: THREE changed sites ship without a reddening case, each for a recorded reason rather than an assumption. countBytesInFilterWithNull (seven measured shapes, no observable face); StatisticsBasic's FixedString branch, whose changed line feeds string_total_bytes, a persisted size estimate (StatisticsBasic.cpp:115,161,273), never a query result; and hasOnlyTypeDefaults, whose sole engine caller sits behind skip_empty_columns_on_insert, false by default (MergeTreeSettings.cpp:213). Corrected before posting, along with the second test and the fixed binary's Build-ID
25 ⚠️ The description carried the pre-round-5 tally, and never addressed the report's own hypothesis. #119633 attributes the wrong result to per-row garbage in the NESTED bytes and asks for the fix in DistinctStep, so "why is this fix somewhere else?" is the first question it raises AGREE, fixed the tally and its taxonomy now read eighteen and 5/5/3/5, recounted from the diff rather than carried forward. On the hypothesis: the nested placeholder never enters the comparison, because the key encoder stops at the null byte for a NULL row (ColumnNullable.cpp:62-64, if (arr[n] == 0) before hashing the nested value; :203-206, if (arr[n]) return a one-byte key). It was the null-map byte that differed, so DistinctStep is not the layer. One clause now says so in the description
26 💡 The second added comment in countBytesInFilterWithNull (ColumnsCommon.cpp:87-88) is redundant with the function-level comment six lines above it, and states the refuted mechanism in the counterfactual rather than the invariant AGREE, noted not blocking the budget is met and not the point: 18 added comment lines against 24 added code lines, longest block 2 lines, 14 comment lines removed. Every other added comment states why a non-obvious domain property holds, which is the class that must NOT be deleted. This one alone is fix-referential, and it is a nit, so it is recorded here rather than made the subject of another round
27 💡 Does the in-tree rule requiring a NativeFormat.mdx update apply to this change? Tested, no update owed tested the rule's own trigger clause, not its topic: it fires on the wire/serialization format, type encodings, block/column structure, the compression frame, NativeReader/NativeWriter, or docs/reference/formats/Native.mdx. This diff touches none of them; it changes in-memory readers and key encoders. And the spec already states the invariant being enforced, verbatim at NativeFormat.mdx:794: "non-zero (canonical 0x01) - Value is NULL". The spec was right and the code was wrong
28 ⚠️ Open question carried into this round: the ColumnVariant::applyNullMapImpl fast path passes the RAW null map to variants[..]->filter(null_map, size_hint), where the filter contract is documented as 0/1 DISAGREE, resolved safe bytes64MaskToBits64Mask (ColumnsCommon.h:21-55) returns ~res with res bit i set for byte i == 0, on the AVX512, AVX2, NEON and scalar-fallback paths alike, so a bit is set exactly when the byte is non-zero; countBytesInFilter is *pos != 0 plus the same-shaped toBits64. IColumn::filter is predicate-correct for every byte value, so that path carries no instance of this defect and needs no change
29 💡 Is the twice-raised if spelling finding actually resolved in the shipped tree, or only in the round it was fixed? Verified resolved swept for backticked name() prose references across both new test files, both reference files, the description, this comment and every added src/ line: zero hits. AGENTS.md:13 is the rule it was raised against

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20260913-030007

@clickhouse-gh clickhouse-gh Bot closed this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no randomization needed: clickhouse local -q "SELECT count() FROM (SELECT DISTINCT if(number % 3, NULL, 'x') FROM numbers(30))" prints 3, must print 2. Fourteen further deterministic faces, including two that lose a whole GROUP BY group, two that replace a present value with NULL, one where max over an all-NULL block returns the empty string instead of NULL, one where dictGetKeys returns 20 keys instead of 10 because a NULL attribute matched a value, and one where an Iceberg data file's statistics claim 60 NULLs in a 30-row file.
b Root cause explained? The Native format defines a null map as a predicate (non-zero means NULL, senders may write any byte) and SerializationNullable reads it back verbatim, so a non-canonical map is valid data. if forwards its raw condition column as the null map, so number % 3 fills it with the bytes 0, 1 and 2, where byte 0 marks the rows holding a value and both 1 and 2 mark rows that are equally NULL. 18 readers treat that byte as a value, so equal NULLs get unequal keys, a scan for the literal 1 declares a block NULL-free, and 1 ^ 2 = 3 turns a present value into NULL.
c Fix matches root cause? Yes: the readers are corrected where they compare the byte wrongly. No widened bound, no no-random-* tag, no reduced dataset, no defensive guard. The producer is deliberately not normalized, because its output is valid per the spec and a producer fix could not repair a part already on disk (measured: the defect survives a MergeTree round trip, so an INSERT-side fix would have passed vacuously).
d Test intent preserved / new tests added? No existing test weakened. Two new stateless tests: 05210_nullable_non_canonical_null_map, with 14 reddening cases plus 2 canonical-map controls, and 05211_iceberg_noncanonical_null_map_statistics, whose oracle asserts that a data file's null_value_counts cannot exceed its record_count (30 60 1 before, 30 20 0 after). Every case was verified to redden individually against the pristine binary; 4 candidate shapes were discarded because they measured identical on both binaries and so could not fail. Three changed sites ship without a reddening case, each with a recorded reason rather than an assumption: countBytesInFilterWithNull (7 measured shapes, no observable face), StatisticsBasic's FixedString branch (feeds only a persisted size estimate, never a query result), and hasOnlyTypeDefaults (its sole engine caller is behind skip_empty_columns_on_insert, which defaults to false, and an all-NULL column then reads back as all NULL either way). One further hunk ships as unreachable-with-a-record: the dictGetKeys vector path, whose row-level hash prefilter drops a non-canonical row before the mask is consulted. Each case's assertion power was then checked against CI's own randomizers, because two randomized settings restore a canonical null map before the reader is reached and a masked run is GREEN: a JIT-compiled conditional stores its null map as select(is_null, 1, 0) (measured to silence the five-argument multiIf case), and a sparse null map is rebuilt from offsets as literal 1 and 0 bytes (measured to silence both cases that read from a part). Pinned with one -- Random settings limits: line per setting rather than a blanket no-random-* tag, and the pin verified in both directions: with it, 8/8 runs report compile_expressions 0 and ratio_of_defaults_for_sparse_serialization 1.0; with its prefix deliberately corrupted, compile_expressions 1 and ratios below the tables' default ratio reappear.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (d5c93699cf443e3e... pristine vs b6d2f89bd1269a82... fixed after round 5's rebuild; rounds 1-4 measured against e69865ae0fcb702a...), each served on its own port with SELECT lower(buildId()) asserted, the pristine one kept side by side for A/B. Repro gate over all 11 faces before: 3 3 1 1 3 20 3 0 20 20 20; after: 2 2 2 2 2 10 2 1 10 10 10; controls unchanged at 2 and 15 in both. The issue's own query: 150 before, 2 after, with GROUP BY at 2 throughout. The full test file was also run end to end on both binaries: the pristine output differs from the shipped reference in exactly the 14 case positions and nowhere else.
f Fix is general across code paths? The invariant was enumerated with PATTERN-based greps (not by variable name), which is what found sites beyond the reported one. 18 carriers fixed; 8 classes of non-carrier recorded with the reason each is excluded (internally-built 0/1 flags, a constraint result column rather than a null map, a reader-built canonical map, unreachable legacy, and integer bitmask arithmetic). Two sibling asymmetries closed: serializeValueIntoMemoryWithNull now agrees with its already-correct arena sibling, and multiIf now matches its own adjacent pseudo-code.
g Fix generalizes across inputs (params/datatypes/wrappers)? One case per SITE rather than per type: Nullable(String) (hashed and arena keys), Nullable(UInt32) (fixed-size key, a different method), Tuple(Nullable(String)) (recursive encoder), LowCardinality(Nullable(String)), a stored MergeTree column, and a Nullable(UInt8) condition through multiIf. Plus Variant(String, UInt8) and Dynamic (the general applyNullMapImpl branch, reached only with two or more non-empty variants), Tuple(Nullable(UInt8)) through a type-changing accurateCastOrNull, an aggregate-combinator Nullable result over String and UInt32, and a stored Nullable(String) dictionary attribute read through a DIRECT layout. Null-map byte values exercised: 0/1/2, 0/2/4 and 2/4/6 (the last has neither a 0 nor a 1, which is what the literal-byte scans and the has-a-value flag look for), with bytes up to 255 probed for the filter-count path. The two SETTINGS axes that would otherwise silence three of these shapes (compile_expressions, ratio_of_defaults_for_sparse_serialization) are pinned per setting, so each shape keeps discriminating under randomization.
h Backward compatible? Yes on canonical data, with one caveat on malformed maps, disclosed in the PR body and the commit message. No setting, no default change, no on-disk format change, so no SettingsChangesHistory.cpp entry. On canonical 0/1 data every changed site is bit-identical, so no existing hash, arena key, packed key, dedup token, stored part or query result moves. On a malformed map the arena key does move, and that key doubles as an aggregation-state format read across server versions (IColumn::SerializationSettings::createForAggregationState), so a state serialized by an older server keeps its raw byte: merging it with a new state can still show two NULL keys for one logical NULL, and groupArrayIntersect, which intersects by exact key, can drop such an element. I add no state versioning, because both bytes deserialize to NULL and the older encoding is the defective one; the affected inputs are exactly the ones this change exists to fix.
i Invariants and contracts preserved? The invariant is stated once and now holds everywhere: a null-map byte is a predicate, not a value, and every reader agrees with isNullAt (!= 0). Keys become more canonical, never less, which is what a 128-bit-hash set that compares no values at all relies on. The replacement scans preserve the empty-range behaviour of the helpers they replace. At both dictionary sites the existing FilterDescription::preprocessFilterColumn is reused rather than open-coding a mask, and it returns a ColumnUInt8 for a plain ColumnUInt8 input too, so the non-nullable path is unchanged. No lock, allocation or block-structure change.

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 max_block_size values, against ~7 settings with randomization off, and all 1200 carried the pinned compile_expressions = 0); SortedEqualRuns.* 13/13 (including the gtest that pins this contract with null-map bytes 1..255), ComputeHashInto.* 38/38, *Nullable* 35/35, *ColumnTuple*/*Variant* 83/83; and 1,599 stateless test executions across nullable, is_null, distinct, group_by, low_cardinality, multi_if, tuple, dictionary, statistics, constraint, each batch run twice (once per binary) with the failure sets diffed, giving zero attributable regressions. Every failure seen locally is a bare-single-server artifact (remote('127.0.0.{1,2}') and test_shard_localhost resolve to localhost:9000, where nothing listens) and reproduces on the pristine binary.

Session id: cron:clickhouse-impl-slot-6:20260912-235300

@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1fd0e1e]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR makes Nullable key encoders and nullness checks interpret every nonzero null-map byte as NULL, and canonicalizes newly generated maps in if. Reviewed head 1fd0e1e8294cfb61470e4aa0e233908c40cfe5d0. Two previously reported upgrade-compatibility blockers remain. Both are deliberate author decisions; no duplicate inline findings were posted.

Findings

❌ Blockers

  • Identical insert retries acquire different identities after upgrading — src/Functions/if.cpp:1250–1256. [dismissed by author -- https://github.com/Treat a Nullable null-map byte as a predicate, not a value #119729#discussion_r4426343775] An INSERT SELECT containing if(toUInt8(number % 3), NULL, materialize('x')) previously produced null-map bytes 0,1,2; this code produces 0,1,1. ColumnNullable::updateHashWithValueRange still hashes those bytes verbatim (src/Columns/ColumnNullable.cpp:67–71), and DeduplicationInfo::calculateDataHashes uses that hash for insert identities (src/Interpreters/InsertDeduplication.cpp:432–440). A retry across versions within the deduplication window therefore inserts another copy. The author's explanation confirms this outcome; requesting canonical output does not preserve retry identities. Provide a compatibility setting or a migration that recognizes the previous identity during the transition.

  • Old and new aggregate states disagree about the identity of the same NULL — src/Columns/ColumnNullable.cpp:203,220,245. [dismissed by author -- https://github.com/Treat a Nullable null-map byte as a predicate, not a value #119729#discussion_r4115674808] Canonicalizing arena keys changes a persisted NULL key from byte 2 to byte 1. groupUniqArray reads and merges the serialized keys verbatim (src/AggregateFunctions/AggregateFunctionGroupUniqArray.cpp:331–373); groupArrayIntersect also intersects those bytes directly (src/AggregateFunctions/AggregateFunctionGroupArrayIntersect.cpp:280–343). Two one-element states that previously agreed can consequently merge into two logically identical elements, or intersect to an empty array. The change at line 245 runs when materializing a result, after these decisions, so it cannot reconcile the keys. The author explicitly documents that saved states remain unrepaired; that disclosure does not prevent incorrect mixed-version merges. Normalize keys before comparison on state loading/merging, with compatible version handling where needed.

Tests
  • ⚠️ Add a retry regression spanning the producer change: perform the same deterministic INSERT SELECT before and after upgrading, retain the deduplication window, and assert that the row count does not increase.
  • ⚠️ The new old-state test only finalizes one state. Merge old/new groupUniqArray fixtures such as 010102 and 010101 for AggregateFunction(groupUniqArray, Tuple(Nullable(String))) and require one element; also verify that equivalent old/new groupArrayIntersect states retain their common element. Exercise both merge orders.

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.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). label Sep 13, 2026
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.
Comment thread src/Columns/ColumnNullable.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e1dbd7792 with master 4d53227b6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of dcccc2b59; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

509 translation units recompiled, 5183 s compile time in total, 509 of them have a recent master baseline.

Job report

…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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@SmitaRKulkarni SmitaRKulkarni self-assigned this Sep 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

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
  • StressHouse run: 6265a7af-ec5f-444b-8694-406dbd0ef1f1
  • MIRAI run: 29850362-d23e-4d78-a924-de2a2b179cd0
  • PR check IDs:
    • clickbench_2645220_1790828203
    • clickbench_2645363_1790828244
    • clickbench_2645476_1790828300
    • tpch_adapted_1_official_2645591_1790828330
    • tpch_adapted_1_official_2645605_1790828331
    • tpch_adapted_1_official_2645625_1790828331

groeneai and others added 2 commits October 15, 2026 12:23
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 327441d

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05345_text_index_prewhere_read_step_order flaky, not from this PR (it changes how a Nullable null-map byte is read, not text indexes): the known read_order_index_first 0 -> 1 diff in the ParallelReplicas lane; it failed on 68 PRs and 12 times on master in the last 30 days #125892 (mine, open)
Mergeable Check, PR praktika rollups of the row above #125892 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261015-200013

@clickhouse-gh

clickhouse-gh Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

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.

@SmitaRKulkarni

Copy link
Copy Markdown
Member

@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.

groeneai and others added 2 commits October 30, 2026 16:10
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 35d1e77: if(cond, NULL, x) now builds its null map as a 0/1 copy of the condition, so if(number % 3, NULL, 'x') writes the bytes [0,1] ([0,1,2] on master; new case in 05210).

The regression tests took their non-canonical maps from if, so they now load the same bytes through format(Native, ...): 05210, 05211, and the cases of 05212, 05224 and 05318 that relied on if forwarding byte 2 (e1dbd77). Their existing result lines are unchanged, and 05210, 05211 and 05224 still fail on a master build.

One side effect: an INSERT SELECT deduplicated by its data hash hashes different null-map bytes than an older server did, so a retry that straddles the upgrade is not recognized as a duplicate.

Comment thread src/Functions/if.cpp
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ [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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

groeneai and others added 2 commits November 15, 2026 15:00
…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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

2 participants