Skip to content

Fix NULL propagation when extracting Nullable, Dynamic, Variant and LowCardinality(Nullable(...)) subcolumns from Nullable(Tuple(...)) columns - #102942

Merged
Avogar merged 29 commits into
ClickHouse:masterfrom
nihalzp:fix-null-propagation-nullable-tuple
Jun 17, 2026
Merged

Avogar merged 29 commits into
ClickHouse:masterfrom
nihalzp:fix-null-propagation-nullable-tuple

Conversation

@nihalzp

@nihalzp nihalzp commented Apr 17, 2026 •

Copy link
Copy Markdown
Member

Given,

SET allow_experimental_nullable_tuple_type = 1;

CREATE TABLE t (tup Nullable(Tuple(s Nullable(String)))) ENGINE = MergeTree ORDER BY tuple();

INSERT INTO t SELECT if((number % 2) = 0, tuple(toString(number)), NULL) FROM numbers(4);

SELECT tup, isNull(tup.s) FROM t;

We get:

   ┌─tup────────┬─isNull(tup.s)─┐
1. │ {         ↴│             0 │
   │↳  "s": "0"↴│               │
   │↳}          │               │
2. │ ᴺᵁᴸᴸ       │             0 │
3. │ {         ↴│             0 │
   │↳  "s": "2"↴│               │
   │↳}          │               │
4. │ ᴺᵁᴸᴸ       │             0 │
   └────────────┴───────────────┘

But should be:

   ┌─tup────────┬─isNull(tup.s)─┐
1. │ {         ↴│             0 │
   │↳  "s": "0"↴│               │
   │↳}          │               │
2. │ ᴺᵁᴸᴸ       │             1 │
3. │ {         ↴│             0 │
   │↳  "s": "2"↴│               │
   │↳}          │               │
4. │ ᴺᵁᴸᴸ       │             1 │
   └────────────┴───────────────┘

Additionally:

SELECT if(number % 2, NULL, tuple(number::Dynamic)::Tuple(a Dynamic)) AS t, t.a
FROM numbers(4)
SETTINGS short_circuit_function_evaluation = 'disable';

We get:

   ┌─t────┬─t.a─┐
1. │ (0)  │ 0   │
2. │ ᴺᵁᴸᴸ │ 1   │
3. │ (2)  │ 2   │
4. │ ᴺᵁᴸᴸ │ 3   │
   └──────┴─────┘

But should be:

   ┌─t────┬─t.a──┐
1. │ (0)  │ 0    │
2. │ ᴺᵁᴸᴸ │ ᴺᵁᴸᴸ │
3. │ (2)  │ 2    │
4. │ ᴺᵁᴸᴸ │ ᴺᵁᴸᴸ │
   └──────┴──────┘

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):

Fix NULL propagation when reading subcolumns extracted from Nullable(Tuple(...)) columns. For example, for tup Nullable(Tuple(s Nullable(String))), SELECT tup.s now correctly returns NULL in rows where the outer tuple is NULL instead of garbage values. This covers all element types that can represent NULL: Nullable, Dynamic, Variant and LowCardinality(Nullable(...)). Closes #105356.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.917

@clickhouse-gh

clickhouse-gh Bot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e8a3e28]

Summary: ✅


AI Review

Summary

This PR fixes NULL propagation for null-carrying subcolumns extracted from Nullable(Tuple(...)), including Nullable, Dynamic, Variant, and LowCardinality(Nullable(...)) element types. After checking the current diff, prior discussion, the new SerializationNullableWithParentNullMap path, range-local null-map application, cache handling, and the added regression tests, I did not find any remaining correctness or safety findings.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 17, 2026
@nihalzp nihalzp changed the title Fix NULL propagation when extracting Nullable subcolumns from Nullable(Tuple(...)) columns Fix NULL propagation when extracting Nullable subcolumns from Nullable() columns (e.g. Nullable(JSON), Nullable(Tuple)) Apr 17, 2026
@nihalzp nihalzp changed the title Fix NULL propagation when extracting Nullable subcolumns from Nullable() columns (e.g. Nullable(JSON), Nullable(Tuple)) Fix NULL propagation when extracting Nullable subcolumns from Nullable(Tuple(...)) columns Apr 17, 2026
@nihalzp
nihalzp requested a review from Avogar April 17, 2026 20:58
@Avogar Avogar self-assigned this Apr 20, 2026
Comment on lines +77 to +79
size_t new_rows = column->size() - prev_size;
if (new_rows == 0)
return;

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.

There are two problems here.

1) column->size() - prev_size is not a reliable way to get the number of rows read in this range. The nested column could already be cached (because we read it during deserialization of another subcolumn). When insert_only_rows_in_current_range_from_substreams_cache is false (the default), insertDataFromCachedColumn may set result_column = cached_column, meaning column ends up pointing to the entire cached column that already contains rows from this range. In that case new_rows will be wrong (or zero), and we won't apply the parent null map.

2) We call column->assumeMutable() and modify the null map in place, but this column might be from cache and shared with another subcolumn, so we would corrupt data visible to other readers.

Example showing problem 1:

CREATE TABLE test (x Tuple(a Nullable(Tuple(b Nullable(UInt32))))) ENGINE = MergeTree SETTINGS index_granularity = 1;
INSERT INTO test SELECT number % 2 ? tuple(NULL) : tuple(tuple(number)) FROM numbers(4);
SELECT x.a, x.a.b FROM test;
┌─x.a──────┬─x.a.b─┐
│ (0)      │     0 │
│ ᴺᵁᴸᴸ     │     1 │  -- x.a.b should be NULL here
│ (2)      │     2 │
│ ᴺᵁᴸᴸ     │     3 │  -- x.a.b should be NULL here
└──────────┴───────┘

The parent null map was not applied to x.a.b.

To fix both issues, let's set insert_only_rows_in_current_range_from_substreams_cache = true before calling the nested deserialization. This forces insertDataFromCachedColumn to copy only the current range's rows via insertRangeFrom instead of sharing the column pointer, so new_rows is reliable and the column has exclusive ownership, making the subsequent mutation safe. This is slightly less performant (an extra copy), but correct. The same approach is used in SerializationVariantElement and SerializationSparse for the same reason.

Note: since settings is passed by reference, the flag should be set on a local copy to avoid leaking it to the caller.

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.

Also, let's keep the order of serialization for consistency - first read the nullmap, then the nested column and then apply the nullmap. It's also good for reading subcolumns in Compact parts so we don't seek backwards in the file.

@Avogar Avogar left a comment

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.

We also need to handle special case when nested subcolumn type is not Nullable but Dynamic/Variant that can also have nulls:

select if(number % 2, NULL, tuple(number::Dynamic)::Tuple(a Dynamic)) as t, t.a from numbers(4) settings short_circuit_function_evaluation='disable';

   ┌─t────────┬─t.a─┐
1. │ {       ↴│ 0   │
   │↳  "a": 0↴│     │
   │↳}        │     │
2. │ ᴺᵁᴸᴸ     │ 1   │
3. │ {       ↴│ 2   │
   │↳  "a": 2↴│     │
   │↳}        │     │
4. │ ᴺᵁᴸᴸ     │ 3   │
   └──────────┴─────┘

select if(number % 2, NULL, tuple(number::Dynamic)::Tuple(a Variant(UInt64))) as t, t.a from numbers(4) settings short_circuit_function_evaluation='disable';

   ┌─t────────┬─t.a─┐
1. │ {       ↴│ 0   │
   │↳  "a": 0↴│     │
   │↳}        │     │
2. │ ᴺᵁᴸᴸ     │ 1   │
3. │ {       ↴│ 2   │
   │↳  "a": 2↴│     │
   │↳}        │     │
4. │ ᴺᵁᴸᴸ     │ 3   │
   └──────────┴─────┘

We need special branches for this when we combine null maps

Comment thread src/DataTypes/NullableUtils.cpp Resolved
@nihalzp nihalzp changed the title Fix NULL propagation when extracting Nullable subcolumns from Nullable(Tuple(...)) columns Fix NULL propagation when extracting Nullable, Dynamic, Variant and LowCardinality subcolumns from Nullable(Tuple(...)) columns Jun 12, 2026
Comment thread src/DataTypes/NullableUtils.cpp Resolved
Comment thread src/DataTypes/NullableUtils.cpp Resolved
Comment thread src/DataTypes/NullableUtils.cpp Resolved
Comment thread src/DataTypes/NullableUtils.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 3 query(s) improved out of 38 analysed

This PR is a correctness fix for reading subcolumns extracted from Nullable(Tuple(...)) columns: it adds a new read-path serialization that applies the parent null map to nested Nullable/LowCardinality/Variant/Dynamic subcolumns. Neither ClickBench nor the TPC-H schema uses Nullable(Tuple) columns, so none of these queries exercise the changed code. Q22 (clickbench) and Q8 (tpch Q8) were downgraded as off-path — Q22's source runs were very noisy and Q8 is a trending join query the diff can't touch. The three large improvements that remain flagged (clickbench Q23 -32%, tpch Q7 -34%, tpch Q20 -48%) are statistically clear and held by the high-magnitude trust gate, but since the changed code is off these queries' execution path, treat them as likely build/environment variance rather than a real speedup from this change.

clickbench

🟢 1 improved · ⚠️ 1 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 23 improvement 297 201 -32.3% <0.0001 aggregation: Large consistent drop held by the trust gate, but this GROUP BY doesn't use the PR's Nullable(Tuple) read path.
⚠️ 22 not_sure 334 253 -24.2% <0.0001 aggregation: Source runs very noisy; PR only touches Nullable(Tuple) subcolumn reads, which this GROUP BY never executes.

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

🟢 2 improved · ⚠️ 1 inconclusive

Flagged queries (3 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 7 improvement 113 75 -33.6% <0.0001 join_operator: Big consistent improvement held on magnitude; join query is off the PR's changed path and history is noisy.
🟢 20 improvement 248 130 -47.6% <0.0001 join_operator: Very large consistent improvement held by the trust gate; noisy query, off the PR's Nullable(Tuple) read path.
⚠️ 8 not_sure 156 185 +19.0% <0.0001 join_operator: Off-path: PR only changes Nullable(Tuple) subcolumn reads; trending history points to run-to-run variance.

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.

Debug info
  • StressHouse run: aa631193-14f4-4fa9-96a2-971eeda053c6
  • MIRAI run: 1d8e1226-8b3f-48b4-9891-2741c23398e7
  • PR check IDs:
    • clickbench_237884_1781614917
    • clickbench_238047_1781615148
    • clickbench_238133_1781615180
    • tpch_adapted_1_official_238242_1781615303
    • tpch_adapted_1_official_238338_1781615343
    • tpch_adapted_1_official_238437_1781615407

Comment thread src/DataTypes/NullableUtils.cpp Resolved
Comment thread src/Columns/ColumnNullable.cpp Resolved
Comment thread src/Columns/ColumnVariant.h Resolved
Comment thread src/Columns/ColumnIndex.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.50% 77.40% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 119/147 (80.95%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 2 line(s) · Uncovered code

Full report · Diff report

@Avogar
Avogar added this pull request to the merge queue Jun 17, 2026
Merged via the queue into ClickHouse:master with commit d425604 Jun 17, 2026
165 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 17, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Jun 23, 2026
Issue ClickHouse#105356 was fixed by ClickHouse#102942, which adds read-path tests for
extracting Nullable, Dynamic, Variant and LowCardinality(Nullable(...))
subcolumns from Nullable(Tuple(...)) columns. None of those tests exercise
a horizontal merge, which is the path that originally aborted the server
with 'Sort order of blocks violated'.

A row stored as outer-tuple = NULL can still carry a non-NULL inner element
on disk. When that element is a sort-key subcolumn, the merge must re-apply
the outer null map; otherwise the reconstructed key disagrees with the
on-disk order and the next OPTIMIZE FINAL aborts in CheckSortedTransform.

This test covers the two carriers ClickHouse#102942 fixes (Nullable(Decimal) and
LowCardinality(Nullable(String))) via SummingMergeTree + OPTIMIZE FINAL.
Deterministic literals (no generateRandom) so it does not depend on
architecture or randomized settings. Verified: aborts on the pre-ClickHouse#102942
binary, passes on current master.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Issue ClickHouse#105356 was fixed by ClickHouse#102942, which adds read-path tests for
extracting Nullable, Dynamic, Variant and LowCardinality(Nullable(...))
subcolumns from Nullable(Tuple(...)) columns. None of those tests exercise
a horizontal merge, which is the path that originally aborted the server
with 'Sort order of blocks violated'.

A row stored as outer-tuple = NULL can still carry a non-NULL inner element
on disk. When that element is a sort-key subcolumn, the merge must re-apply
the outer null map; otherwise the reconstructed key disagrees with the
on-disk order and the next OPTIMIZE FINAL aborts in CheckSortedTransform.

This test covers the two carriers ClickHouse#102942 fixes (Nullable(Decimal) and
LowCardinality(Nullable(String))) via SummingMergeTree + OPTIMIZE FINAL.
Deterministic literals (no generateRandom) so it does not depend on
architecture or randomized settings. Verified: aborts on the pre-ClickHouse#102942
binary, passes on current master.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Another Sort order of blocks violated for column

4 participants