Repository navigation
Allow ColumnNullable without a null map - #125013
alexey-milovidov wants to merge 68 commits into
Conversation
A `Nullable` column that has no NULLs can now hold no null map at all. The null map is created lazily (and thread-safely, as columns are shared) by the accessors returning it by reference, so the code that is not aware of this keeps working; the profile event `NullableNullMapMaterializations` counts these cases. The columns without a null map are produced by `makeNullable`, `DataTypeNullable::createColumn`, the default implementation of functions for `Nullable` arguments, logical functions, `if`, aggregate function results, aggregation keys, and when reading data without NULLs (e.g. from MergeTree or in the `Native` format). The on-disk and wire formats are unchanged: a zero-filled null map is written without being created. The column operations, serialization, aggregation (`-Null` and `-If` combinators, `count`, hash methods for nullable keys), sorting, filtering, JIT and logical functions are specialized for the columns without a null map. #124762 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [efca9f0] Summary: ❌
|
|
📊 Cloud Performance Report 🟢 AI verdict: This PR makes the Nullable null map optional, with fast paths in aggregate combinators, hashing, filtering and sorting. The one confident result is a large improvement on clickbench Q20 (-44.5%, 220 ms to 122 ms), where CPU time per run also halves. That result is locked in by the deterministic checks, but the standard ClickBench schema has no Nullable columns, so its link to this change is not obvious and should be confirmed with a rerun. Q28 is borderline with very noisy runs, and the 6-7% gains on Q33/Q34 fall inside master's normal range for those queries; these suppressions are consistent with the data and the diff. clickbench🟢 1 improved · Flagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…getPlanes` The hash join gather path calls `getPlanes` on the stored right-side columns, and `ColumnNullable::getPlanes` used `getNullMapData`, which lazily created a zero-filled null map for a column without one. That defeated the memory saving and changed `allocatedBytes` of the blocks after `HashJoin` had accounted for them, so the debug check `data->allocated_size != debug_allocated_size` threw a logical error (e.g. in `02274_full_sort_join_nodistinct` with `grace_hash`, and in `test_prometheus_protocols`). Expose the shared zeros via `getNullMapRawDataOrZeros` instead. Also skip the NULL filtering of the ASOF key without creating the null map when the column has none. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125013&sha=latest&name_0=PR PR: #125013 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The null map created on demand changes `allocatedBytes` of a column after it was accounted, which triggered `data->allocated_size != debug_allocated_size` in `HashJoin::doDebugAsserts` (test `01881_join_on_conditions_hash`): the join mask of a `Nullable(UInt8)` condition without a null map created its null map. Fixed the places that created the null maps of the columns that can be stored in a hash join or shared: the join mask, `isNull`, `isNotNull`, `getPlanes`, the `ASOF` key filter, `probeFixedHashMap`, `insertFromNullableOrDefault`, `correctNullabilityInplace`. The join tests were run with the debug assertion enabled. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125013&sha=latest&name_0=PR&name_1=Stateless%20tests%20(amd_debug%2C%20parallel) #125013 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nullable-without-null-map # Conflicts: # src/Columns/ColumnNullable.cpp # src/Interpreters/HashJoin/HashJoin.cpp
…-without-null-map
Build profile diff (arm_release)Commit See the job log for details. |
If the NULLs of the `Nullable` branches of `if` are not selected, the result null mask is all zeros. Drop it, so the result has no null map and the downstream operators can use the path without a null map. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tionNullable::enumerateStreams` For a `Nullable` column without a null map, the zero-filled `null` subcolumn was created eagerly for every call of `enumerateStreams`, including extraction of other subcolumns in memory. Use a lazy column creator, so it is created only if the `null` subcolumn is requested. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…IT compilation With `compile_expressions = 1`, `if` is compiled, and the compiled function returns a `Nullable` column with a null map. The test checks the structure of the interpreted implementation, so pin `compile_expressions = 0`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125013&sha=2f2fd35fe17baf4db7b93c9affd2f82f004a2d3e&name_0=PR PR: #125013 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…erialization The row-wise deserializers of `SerializationNullable` (`deserializeBinary` and the text formats) accessed the nested column with `getNestedColumn`, and `safeAppendToNullMap` always appended to the null map, so reading `CSV`, `TSV`, `JSONEachRow`, `Values`, etc. materialized an all-zero null map on the first row. Use `getNestedColumnNoMaterialize`, and create the null map only on the first NULL. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tring` `copyNullMap` called `getNullMapColumn`, which materialized the null map of the source column, and the results of `toString`, `FixedString` to `String`, and the date/time formatters always carried a null map. Do not materialize the source null map, and drop the result null map with no NULLs in `createNullableResult`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…oString` Co-Authored-By: Claude Opus 5.5 <[email protected]>
…methods The per-block fast path in `HashMethodBase` searched the null map only for the byte `1`, but `ColumnNullable` treats any non-zero byte as NULL. Check that the whole null map is zero. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`getNullMapRawDataOrZeros` and `getPlanes` expose it in place of a `PaddedPODArray`, and the readers (e.g. `memcpySmallAllowReadWriteOverflow15` in `GatherUtils`) may read past the end. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The readers of a `Nullable` column without a null map may create it lazily. For a block stored in `HashJoin` this happened after the block was accounted in `data->allocated_size`, so the accounting drifted and the debug check threw `data->allocated_size != debug_allocated_size` (`test_prometheus_protocols` under MSan: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125013&sha=d9eadcb3c9e7fe6fb1a5731703fcf6ea3fde9533&name_0=PR&name_1=Integration%20tests%20%28amd_msan%2C%20targeted%29). Instead of finding every reader that creates the null map, `StoredBlock` creates the null maps of its columns when it is constructed or its columns are replaced, so the accounted size is stable. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged master and pushed fixes:
|
…e` result Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ison when it has no null map A `Nullable` column with no rows may now have no null map, so the check that all gathered elements of a `Nothing` side are NULL must not require a null map when there are no elements. This fixes `04549_array_comparison_bigger_types_nullable` and `04767_array_lexicographic_nothing_element`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125013&sha=a92346239f7aadfb0a5960b45854b61a2cf6046d&name_0=PR&name_1=Fast%20test #125013 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 At eb7045d every check passed except one, It failed on CI infrastructure, not on this PR: There are no unresolved review threads and no conflicts. The branch is one day behind |
Resolved the conflict in `RowDataStore.cpp` by taking master's version, where the row gathering moved into `IColumn::gatherRangeIntoRows`; `ColumnNullable` now passes `getNullMapRawDataOrZeros` there because a const column may have no null map.
…rom master `HashedJoinKey::addParts` and `parquetTryHashColumn` came from master and used the const `getNullMapData`, which no longer exists because a `ColumnNullable` may have no null map. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mbly On `OS_WASM`, an anonymous `mmap` is allocated and zeroed in the linear memory, which is limited to 16 GiB, so the 64 GiB virtual zero mapping returned by `getNullMapRawDataOrZeros` cannot be created. Allocate a zero buffer of the requested size there instead, growing it geometrically. The previous buffers are never freed, because readers may still hold pointers to them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failures: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125013&sha=5b4da72f676e7ecb5686edb9dcb26b1bfcc1a5fc&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 ( |
|
|
Follow-up to 2. ( Every group, even one inside a chunk, went through the sliding window of Local release A/B (no ThinLTO, the perf test's tables and queries, 12 rounds): |
…up window
`NegativeLimitBySortedStreamTransform::consume` sent every group, even one
that starts and ends inside the current chunk, through the sliding window:
`append_run` pushed a `ChunkSlice` into the empty window deque (allocating the
deque map and a block, and copying the chunk `shared_ptr`), `finalizeWindow`
copied it into `pending` (a second `shared_ptr` copy) and then `window = {}`
(libc++: `clear(); shrink_to_fit();`) freed the block and the map. So each
one-row group cost two memory-tracked allocations, two frees and two atomic
increment/decrement pairs, plus one `pending` entry.
The window is only needed for a group that touches a chunk boundary. A group
that ends inside the chunk while the window is empty also started inside this
chunk, so its output is known when its end is found: the last
`min(L, length + offset)` rows of the run without the trailing `offset` rows,
the same rows `append_run` + `dropExcessRows` + `dropOffsetRows` keep for a
one-slice window. Such groups are now staged into `pending` directly, and
`appendToPending` extends the last pending slice when the new rows continue
it in the same chunk, so the one-row groups of a chunk become one slice.
`generate()` produces the same chunk for a merged slice (same rows, first
start and last end). Groups touching a chunk boundary still use the window.
Evidence that this path is what moves the `negative_limit_by_in_order`
queries #0, ClickHouse#1 and ClickHouse#8 (millions of groups): ClickHouse#125000, which changed only the
allocator of these deques, moved them by -19/-16/-17% on master d3ee313 while
ClickHouse#2-ClickHouse#7 stayed flat; and the ClickHouse#125013 perf job's prewarm counters for #0 show
equal instructions on both sides (10301M vs 10333M, ~1030 per group) and +15%
cycles on one build.
Local A/B (release build, `CMAKE_BUILD_TYPE=None`, no ThinLTO, the perf
test's tables and queries, 12 rotating rounds, geomean of per-round ratios
new/base with bootstrap 95% CI):
#0 10M one-row groups 0.764 s -> 0.096 s 0.123 [0.113, 0.135]
ClickHouse#1 1M groups of 10 0.098 s -> 0.049 s 0.457 [0.413, 0.510]
ClickHouse#2 100k groups of 100 0.025 s -> 0.019 s 0.707 [0.642, 0.785]
ClickHouse#3-ClickHouse#7 100 groups 0.86-1.03, no CI lower bound above 1.0 (4-15 ms)
ClickHouse#8 5M two-key groups 0.447 s -> 0.116 s 0.250 [0.236, 0.265]
User-space instructions of 5 runs of #0: 60.3G -> 10.2G (~1190 -> ~190 per
group after subtracting 5 runs of ClickHouse#3), cycles 16.2G -> 3.1G; ClickHouse#8: 31.4G ->
6.4G instructions. In the base profile of #0 about half of the samples are
in the deque allocation, `shrink_to_fit`, `CurrentMemoryTracker` and
jemalloc; none of them is in the top 15 after the change.
Replacing only `window = {}` by `clear()` (keeps the deque blocks) gives
0.526 / 0.594 / 0.583 on #0 / ClickHouse#1 / ClickHouse#8, so the direct staging is 4.3x and
2.3x faster than that on #0 and ClickHouse#8.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Storages/ObjectStorage/DataLakes/Iceberg/DataFileStatistics.cpp
…om master `HashedDictionary`, `arrayTreePreorder` and `matchORCTupleElementsByName` came from `master` with calls of the const `getNullMapData` and `getNullMapColumnPtr`, which this PR removed. Use `tryGetNullMapData` and `tryGetNullMapColumnPtr`; the callers already handle a missing null map. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Thanks @groeneai: the At 149dad3 I merged |
…ll-map Conflicts were resolved by taking the refactorings from master (`mergeNullMaps`, `extractTupleElementConversionFailures`, `Set::castToKeyType`, `gatherFromRows`, `createColumnForDeserialization`, `probeFixedHashMap` moved to `HashJoinTable.cpp`) and adapting them to columns without a null map: the null map is read with `tryGetNullMapColumnPtr` / `tryGetNullMapData` / `tryGetNullMapColumn`, and a missing null map means no NULLs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…om master `PuffinColumnThetaSketch::update`, the tuple gathering in `RowDataStore` and `getDateTime64CastLossMap` used the const null map accessors removed in this PR. A `Nullable` column without a null map has no NULLs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ll-map Conflicts are with the ownership assertions in `assumeMutable` and `assumeMutableRef` added in master: - `ColumnNullable::create` from immutable columns uses `const_cast` + `getPtr` like in master, also for a column without a null map; - the constructor of `ColumnNullable`, `materializeNullMapSlow` and `shrinkToFit` read the possibly shared subcolumns through the const view; - `ColumnArray::replicateNullable`, `wrapInNullable`, `arrayReverse`, `SerializationNullable` and `gtest_column_array` keep the handling of a column without a null map on top of the changes from master. Co-Authored-By: Claude Fable 5.2 <[email protected]>
- `packedTupleColumns` in `RadixUniqExactTransform` reads the null map with `getNullMapRawDataOrZeros`. - `popBackBorrowed` and `insertDefaultBorrowed` in `ProtobufSerializer` used the const `getNullMapColumnPtr`, which no longer exists. Popping rows skips an absent null map, and inserting a default (NULL) row creates the null map first. Co-Authored-By: Claude Fable 5.2 <[email protected]>
… on WebAssembly On `OS_WASM`, the first `getZeros(0)` returned nullptr, because the cached size was already enough while nothing was allocated yet. The callers use the presence of the pointer to enable the processing of NULLs, so `arrayElement` on an empty `Array(Nullable(UInt8))` column threw a logical error exception. Require an allocated buffer in both early returns. Co-Authored-By: Claude Fable 5.2 <[email protected]>
… packing fixed keys `createBitmap` in `ColumnsHashingImpl.h` and `SetVariants.h` recognized only the byte 1 as NULL, and `encodeFixedSizeKeys` in `DiskSetKeys.cpp` packed the raw byte into one bit. A null map with other nonzero bytes (e.g. read from the `Native` format) was grouped by the nested values under NULL. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125013&sha=469ce0287aaf74aa927c174eac2a73b30e21772a&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%205%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. The job |
|
The fix is in progress in #132767 (mine, open). Only 5/6 failed at 469ce02; the other five shards finished in 67-103 min. Each shard gets 107 of the 642 selected tests, split round robin by file name, and every selected test runs all its queries ( #132767 assigns the selected tests to shards longest first by their measured runtimes. Replaying this run's 642 tests, the per-shard |
|
📊 Cloud Performance Report ✅ AI verdict: No query has a verdict that blames this PR. Three ClickBench aggregation queries ran slower: Q10 (+21.7%), Q30 (+15.3%) and Q31 (+10.5%). All three timings are still inside the range master itself produces right now, and all three queries have noisy history, so the checks held them back as inconclusive. That outcome fits the diff: the PR lets a Nullable column skip its null map when it has no NULLs, but these queries group by and aggregate ClickBench columns that are not Nullable. The tested patch was cut short, so not every changed file could be checked, but nothing found ties these slowdowns to the change. clickbenchFlagged queries (3 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
The code that came with the merge of `master` called the removed const methods `getNullMapData` and `getNullMapColumnPtr`: the promotion checks of the JSON conversions in `FunctionsConversion.cpp` and `replaceTimestampsStoredAsEpoch` in the ORC writer. They now read the null map with `tryGetNullMapData` and `tryGetNullMapColumnPtr`, and treat a missing null map as no NULLs. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…nary aggregates and serialized keys `AggregateFunctionNullUnary::addBatchSinglePlace` set the flag of a non-empty result unless all bytes of the null map were 1, so a batch with only NULLs marked by other nonzero bytes (e.g. read from the `Native` format) returned 0 or `nan` instead of NULL. The flag is now set only if the batch has a zero byte. `serializeValueIntoMemoryWithNull` and `batchSerializeValueIntoMemoryWithNull` copied the raw byte of the null map into the serialized key, so two NULLs with different nonzero bytes were different keys in `GROUP BY`. They now write 1, as `serializeValueIntoArenaWithNull` does. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged Both open review threads are addressed in efca9f0 with the new test Thanks @groeneai for the analysis. The only test failure at bfeeaf0 was the same kind: |
A
Nullablecolumn that has no NULLs can now hold no null map at all, as proposed in the issue. This saves memory and lets the algorithms skip the null handling.The column stays immutable: a reader never creates a missing null map in place. The const methods returning the null map by reference are removed, and every reader checks for the null map with
hasNullMap,tryGetNullMapData,tryGetNullMapColumn, ortryGetNullMapColumnPtrand takes a faster path when it is absent, or reads it throughgetNullMapRawDataOrZeros(a pointer to a shared read-only zero mapping). Only the non-const methods (getNullMapData,getNullMapColumn,getNullMapColumnPtr,getNestedColumn) create the null map, because their caller owns the column and modifies it. The new profile eventNullableNullMapMaterializationscounts these cases.The columns without a null map are produced by
makeNullable,DataTypeNullable::createColumn, the default implementation of functions forNullablearguments, logical functions,if, aggregate function results and aggregation keys, and when reading data without NULLs (from MergeTree, in theNativeformat, etc.). The on-disk and wire formats are unchanged: a zero-filled null map is written without being created.The column operations, serialization, aggregation (
-Nulland-Ifcombinators,count, hash methods for nullable keys), sorting, filtering, JIT and logical functions are specialized for the columns without a null map. The hashes and the serialized aggregation keys are the same with and without a null map. The places that still created the null map were found by running NullableClickBench (ClickBench with all columnsNullable) with a breakpoint on the creation of the null map, and fixed.By itself, this change does not make NullableClickBench measurably faster (the null maps without NULLs are cheap to process), the speedups for it are in #125011. It is a prerequisite for not writing and not sending the null maps without NULLs at all, which is done in a follow-up.
All stateless tests were run with this change and without it in
clickhouse-local, and the results were compared; the only differences are in the output ofdumpStructure, which no longer shows an empty null map.Related: #124762
Related: #125011
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Nullablecolumns without NULLs do not keep the null map in memory, and many operations skip the processing of NULLs for them.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/125013]