Skip to content

Support Nullable(Array) - #104816

Closed
zhanglistar wants to merge 106 commits into
ClickHouse:masterfrom
bigo-sg:nullable-array
Closed

zhanglistar wants to merge 106 commits into
ClickHouse:masterfrom
bigo-sg:nullable-array

Conversation

@zhanglistar

@zhanglistar zhanglistar commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Experimental Feature

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

#105192
Add support for Nullable(Array). Set allow_experimental_nullable_array_type = 1 to enable it.

@Avogar

Avogar commented May 13, 2026

Copy link
Copy Markdown
Member

Hi @zhanglistar! Thank you for creating this PR. Unfortunately, proper support for Nullable(Array) is significantly more complex than what this PR covers. There are several fundamental problems that need to be addressed, and it would require a thorough design discussion (RFC) before implementation. Below is a (non-exhaustive) list of major issues:

1) MergeTree serialization stream name collisions

The stream names for substreams in MergeTree are generated by getNameForSubstreamPath in ISerialization.cpp. For Nullable, it appends .null, for Array, it appends .size0. The enumeration order matters: SerializationNullable::enumerateStreams emits the null map first, then wraps the nested type under NullableElements, SerializationArray::enumerateStreams emits ArraySizes first, then wraps nested elements under ArrayElements.

For a column c of type Array(Nullable(UInt32)), the streams are: c.size0, c.null, c.
For a column c of type Nullable(Array(UInt32)), the streams would be: c.null, c.size0, c.

Now consider Nullable(Array(Nullable(UInt32))) — you'd get two .null streams at different nesting levels colliding with the same name c.null. Solving this requires reworking the stream name generation logic and careful handling of backward compatibility for existing MergeTree parts.

2) Function execution framework assumptions

In IFunction.cpp:211-268, when a function has nullable inputs but cannot produce a nullable result (e.g., returns Array, Tuple, Map), the framework applies special "patch" logic: it replaces null rows with default values and executes the function on the unwrapped nested columns. This entire code path is built on the assumption that Array results are never Nullable. With Nullable(Array), the function framework needs to be redesigned to handle cases where the result type itself can be Nullable(Array(...)) with compatibility considerations.

3) Pervasive canBeInsideNullable checks across the codebase

There are 70+ files that check canBeInsideNullable. Each one encodes an assumption about what types can be nullable. Key places beyond the obvious gatekeeper in DataTypeNullable constructor:

  • getLeastSupertype.cpp:358 — type coercion decides whether to wrap results in Nullable
  • CastOverloadResolver.cpp:46 — accurateCastOrNull validation explicitly excludes types that can't be nullable
  • NullableUtils.cpp:34-52 — canExtractedSubcolumnsBeInsideNullable and related helpers
  • NestedUtils.cpp:170 — unwrapNullableTuple has special handling that replaces null values of non-nullable-capable types with defaults
  • FunctionToSubcolumnsPass.cpp:695-702 — disables subcolumn optimizations when nullability context could differ

All these places require consideration, especially in terms of compatibility.

4) 200+ direct ColumnArray casts in functions

Across src/Functions/, there are 200+ places doing checkAndGetColumn<ColumnArray>(col) or typeid_cast<const ColumnArray &>(col), all of which assume the column is not wrapped in ColumnNullable. The PR patches a few (arrayElement, FunctionArrayMapped), but the vast majority of array functions remain unhandled. Each one needs auditing and potentially wrapping/unwrapping logic.

5) SerializationNullable::enumerateStreams subcolumn creator logic

At SerializationNullable.cpp:62, the NullableSubcolumnCreator is only set when type->canBeInsideNullable() returns true. This controls how subcolumns are extracted from nullable columns. For Nullable(Array), this path would need to work correctly and propagate null maps through subcolumn reads (e.g., reading .size0 from a Nullable(Array) should return Nullable(UInt64), not UInt64).

6) Aggregate functions

Aggregate functions like groupArray have their own null-handling logic that operates at the scalar element level. With Nullable(Array), the semantics of "null" change — is a null array the same as an absent value? How should groupArray handle null arrays vs empty arrays? This needs specification.

7) Format compatibility

While the PR updates Arrow/ORC/Parquet readers, other formats (JSON, CSV, TSV, etc.) and their schema inference logic (SchemaInferenceUtils.cpp) also need updating. The adjustNullableRecursively function and related inference code have assumptions about what types can be nullable during schema inference.

Given the scope and the risk of subtle bugs (especially around MergeTree data corruption from stream name collisions), this feature would benefit from an RFC that covers:

  • Stream naming scheme redesign with backward compatibility plan
  • Semantics specification (e.g., what does NULL mean for aggregations, JOINs, GROUP BY)
  • A comprehensive audit plan for the 200+ affected call sites in functions

We plan to work on this in the core team eventually, but it currently doesn't have a set timeline. We appreciate the interest and effort — this is a real and frequently requested feature, and the exploration in this PR is useful context for when we take it on.

@alexey-milovidov

alexey-milovidov commented May 14, 2026 •

Copy link
Copy Markdown
Member

Thank you! This is a great PR, and it will greatly improve ClickHouse interoperability!
The most important thing - we shall not be afraid. Let me answer questions from @Avogar

  1. MergeTree serialization stream name collisions

For Nullable(Array) one stream will be named null as usual, and the stream for values will be named nested (not an empty path-name component as for other Nullable types).

  1. Function execution framework assumptions

It will be controlled with a compatibility setting. Under the old compatibility, functions that return an Array and might want to make it Nullable, will still use the old path in the code, returning non-Nullable Array.

  1. Pervasive canBeInsideNullable checks across the codebase

Implement and see what will break and how to proceed further. Implementation is cheap.

  1. 200+ direct ColumnArray casts in functions

This is ok, most functions will work through defaultImplementationForNullable.

  1. SerializationNullable::enumerateStreams subcolumn creator logic

Ok, we will have to do it.

  1. Aggregate functions

Skip nulls as every aggregate function does by default.

  1. Format compatibility

With a compatibility setting.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4287142]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
04615_nullable_array_format_null_as_default FAIL cidb
Code Review DROPPED
Docs check DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 14, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Recently, we introduced Nullable(Tuple) and we found an enormous amount of corner cases with that, and it took multiple months to fix them. It was one of the main reasons for improving CI coverage and hardening. But now we have even stricter CI and even more fuzzing, so we are ready for the next step!

Comment thread src/DataTypes/DataTypeArray.h Resolved
@zhanglistar zhanglistar reopened this May 15, 2026
@zhanglistar

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov Thanks for your reply, let me have a try @Avogar. Anyway it's a try whether it will be merged or not. I'll try my best to do it.

Comment thread src/DataTypes/DataTypeArray.h Resolved
@zhanglistar
zhanglistar marked this pull request as draft May 18, 2026 03:01
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
…red substream names and cache keys.

Assign unique structured stream suffixes at every array nesting level, and use
the same keys in SubstreamsCache during deserialization to avoid colliding
outer and inner null maps.
Comment thread src/Functions/array/arrayIndex.h Resolved
Comment thread src/Functions/array/arrayReduce.cpp Resolved
Comment thread src/Functions/array/arrayFold.cpp Resolved
Respect allow_experimental_nullable_array_type when wrapping array-valued subcolumns extracted through an outer Nullable column. This keeps Nullable(JSON) array paths compatible when random settings disable the experimental Nullable(Array) type.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104816&sha=7944b5d0e40cace70422529447e1699f14b8167a&name_0=PR&name_1=Stateless+tests+%28arm_binary%2C+parallel%29&name_2=Tests

PR: ClickHouse#104816
Old analyzer can keep casts as Const(Nullable(Array(...))). Several nullable-array helper paths only detected ColumnConst through checkAndGetColumnConst<ColumnConst>, so they missed the outer constant wrapper and passed Const(Nullable(Array(...))) into array execution paths that expect ColumnArray.

Use checkAndGetColumn<ColumnConst> before inspecting the data column so mapped array functions, arrayFold, arrayReduce, and array arithmetic unwrap const Nullable(Array) arguments consistently.

Related: ClickHouse#104816

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104816&sha=930b8941d0bff0f02fd904a96f6a30bd16120b53&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%201%2F3%29
@zhanglistar
zhanglistar marked this pull request as ready for review July 23, 2026 09:17
@zhanglistar
zhanglistar marked this pull request as draft July 23, 2026 09:53
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 3212/3670 (87.52%) · Uncovered code

Full report · Diff report

Move allow_experimental_nullable_array_type to the 26.8 settings history block so upgrade checks from 26.7 see it. Preserve nullable-array missing/default handling in external format readers and extracted subcolumns. Narrow the upgrade log allow-list for the system.metric_log_0 readonly warning and adjust focused stateless coverage.

Related: ClickHouse#104816

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104816&sha=263d7f95798980e19f9c5ccc5cbe7093c36ae78d&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104816&sha=263d7f95798980e19f9c5ccc5cbe7093c36ae78d&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 24, 2026
@zhanglistar
zhanglistar marked this pull request as ready for review July 25, 2026 00:53
@zhanglistar

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov @Avogar Almost make all CI success, pls take a look if you have time.

# Conflicts:
#	src/DataTypes/DataTypeNullable.cpp
#	src/DataTypes/Serializations/ISerialization.cpp
#	src/Interpreters/InterpreterCreateQuery.cpp
#	src/Interpreters/InterpreterCreateQuery.h
#	src/Processors/Formats/Impl/ORCBlockInputFormat.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Status check against current master (head 4287142a), since you asked for a look.

1. The three open AI-review threads are already addressed at your current head — I re-verified each against 4287142a:

  • ArrowColumnToCHColumn.cpp (nullable LIST with the setting disabled): the LIST/LARGE_LIST/FIXED_SIZE_LIST branch now throws CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN when array_type_hint && !isNullableOrLowCardinalityNullable(type_hint) && arrow_column->null_count() && !null_as_default, and preserve_list_nulls_for_defaults keeps the parent bitmap on the null_as_default path. ✅
  • NativeORCBlockInputFormat.cpp: the orc::LIST branch has the matching orc_list_column->hasNulls && !null_as_default check. ✅
  • NullableUtils.cpp: all three NullableSubcolumnCreator::create overloads now special-case Array before canExtractedSubcolumnsBeInsideNullable, so the outer-nullable creator path keeps the parent null map while bare Array(T).null dynamic paths stay rejected — exactly what the review asked for. ✅

These threads can be resolved.

2. The PR is CONFLICTING with master. Four files conflict; three are ordinary content conflicts (NativeORCBlockInputFormat.cpp, AlterCommands.cpp, MergeTreeReaderCompact.cpp), but one needs real work:

src/Processors/Formats/Impl/ArrowBlockInputFormat.cpp was deleted on master by 559f3d4 ("Remove the Apache Arrow library reader and writer for the Arrow formats"). Your change to it is only the schema_inference_allow_nullable_array_type addition to the schema-inference cache key, so the file itself can just be dropped — but the surrounding work needs re-pointing:

  • The cache-key line moves to src/Processors/Formats/Impl/ArrowIPC/ArrowIPCBlockInputFormat.cpp (the schema_inference_allow_nullable_tuple_type={} format strings around lines 1392 and 1409).
  • More importantly, ArrowColumnToCHColumn is no longer used by the Arrow or Parquet formats on master — only by Arrow Flight and DeltaLake. The Arrow format now reads through ArrowIPC/RecordBatchDecoder.cpp and infers schema through ArrowIPC/SchemaConverter.cpp (see the existing schema_inference_allow_nullable_tuple_type handling in both — that is the pattern your nullable-array handling has to follow there). Your ArrowColumnToCHColumn.cpp changes stay valid for Flight/DeltaLake, but the Arrow-format coverage and its tests need to be ported to the new reader, otherwise it will silently regress.

3. CI is stale. The last reports are for 263d7f95 (2026-07-24), before your 07-28 merge commit. Of those failures:

  • 04237_nullable_array_drop_column_streams (Fast test arm_darwin) — you already fixed the reference afterwards; note the test no longer lists any streams before the drop, so it only checks the "after" state now.
  • 04312_client_chime_on_slow_query_92718 — flaky, unrelated.
  • The Upgrade check settings-history failures also list join_runtime_filter_min_probe_rows, a master-side setting, so that one is not specific to this PR.

Merging master and re-running CI should give a clean picture once the Arrow re-porting is done.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Follow-up to my status check yesterday — two corrections/updates after a deeper pass over head 4287142a:

1. The Arrow IPC re-port I flagged is in fact already done at your head. ArrowIPC/RecordBatchDecoder.cpp already carries the full nullable-array handling (the CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN throw for a non-nullable Array hint with input_format_null_as_default = 0, and the Nullable wrap on the null_as_default = 1 path), and ArrowIPC/SchemaConverter.cpp handles schema_inference_allow_nullable_array_type. Sorry for the noise — the remaining Arrow work is smaller than I said:

  • When you merge current master, add schema_inference_allow_nullable_array_type to the schema-cache keys in src/Processors/Formats/Impl/ArrowIPC/ArrowIPCBlockInputFormat.cpp (the two schema_inference_allow_nullable_tuple_type={} format strings, currently around lines 1392 and 1409 on master). Those cache keys were added to master after your 07-28 merge and the file does not conflict, so this is easy to miss silently — without it, cached inferred schemas leak across different values of the setting.
  • src/Processors/Formats/Impl/ArrowBlockInputFormat.cpp (deleted on master) can just be dropped in the merge; the cache-key line above is its only surviving piece.

2. The five newer AI-review threads (07-21/07-22) are also all addressed at your current head — I verified each against 4287142a:

  • ArrowIPC/RecordBatchDecoder.cpp (both threads): nullable_array_allowed now includes explicit_non_nullable_array_hint && settings.null_as_default, so the decoder keeps the outer list null map as Nullable(Array); ArrowIPCBlockInputFormat::buildChunk then runs insertNullAsDefaultIfNeeded, which sets BlockMissingValues and substitutes defaults. ✅
  • Parquet/Reader.cpp: on the null_as_default = 1 path the reader now calls block_missing_values.setBitsFromNullMap from nullable_array_null_map before dropping the wrapper. ✅
  • ArrowColumnToCHColumn.cpp: preserve_list_nulls_for_defaults keeps the wrapper through to insertNullAsDefaultIfNeeded. ✅
  • NativeORCBlockInputFormat.cpp: the nullable-wrap condition now includes type_hint_is_non_nullable_array && null_as_default, with the same insertNullAsDefaultIfNeeded handoff. ✅

The exact reviewed scenario (arr Array(Int32) DEFAULT [42] receiving a top-level NULL list) is pinned by 04615_nullable_array_format_null_as_default.sql across Parquet, Arrow (native and library reader), ArrowStream, and ORC. So all eight open review threads can be resolved.

What actually remains is just the master merge: the same four conflicted files as before (NativeORCBlockInputFormat.cpp, AlterCommands.cpp, MergeTreeReaderCompact.cpp, plus dropping ArrowBlockInputFormat.cpp), the cache-key addition above, and a fresh CI run.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 CI has now run on your current head 4287142a and there is exactly one failing test — and it is a trivial, mechanical fix.

Fast test → 04615_nullable_array_format_null_as_default:

Code: 73. DB::Exception: Unknown format Parquet. (UNKNOWN_FORMAT)
(query: INSERT INTO FUNCTION file(04615_nullable_array_format_null_as_default.parquet, Parquet) ...)

The fast-test build is compiled without Arrow/Parquet/ORC, so any test using Parquet, Arrow, ArrowStream or ORC must be excluded from it. Add the standard tag as the very first line of tests/queries/0_stateless/04615_nullable_array_format_null_as_default.sql:

-- Tags: no-fasttest

Everything else in that report is green (12820 tests, 1 failure).

Two remaining items from my earlier passes, unchanged:

  1. The PR is still CONFLICTING against master. Conflicts: NativeORCBlockInputFormat.cpp, AlterCommands.cpp, MergeTreeReaderCompact.cpp (content), and ArrowBlockInputFormat.cpp — the latter was deleted on master by 559f3d411d7, so just drop it.
  2. When you merge master, note that master has since added schema-inference cache keys in ArrowIPC/ArrowIPCBlockInputFormat.cpp (schema_inference_allow_nullable_tuple_type={}). That file does not conflict, so please remember to add schema_inference_allow_nullable_array_type to the same cache key, otherwise inferred schemas leak across different values of the setting.

All 8 open clickhouse-gh review threads are addressed at your current head (I re-verified each one) — they can be resolved.

I cannot push these for you: maintainer edits are disabled on the bigo-sg/ClickHouse fork.

@yakov-olkhovskiy

yakov-olkhovskiy commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

🕵

Assessment of the current state

I went through this PR at head 4287142a against current master, alongside the RFC in #105192 and the blocker list in @Avogar's review. Posting the assessment first; a proposed plan follows in a separate comment.

Short version: all seven blockers from that review are substantively addressed. This is no longer an exploratory patch. What remains is largely about evidence and reviewability rather than missing functionality.

The design decision that answers most of the list

DataTypeArray::canBeInsideNullable still returns false. The PR never flips it. Instead, DataTypeNullable gains a private two-argument constructor reachable only through a friend function, makeNullableAllowingArray, so Nullable(Array) can only be constructed by the ~49 sites that opt in explicitly.

This is exactly what the RFC promised, and I think it is the right call. It answers blocker 3 ("70+ files check canBeInsideNullable") not by auditing 70 files but by leaving the predicate's meaning unchanged, so no existing code path can spontaneously begin producing Nullable(Array). It is also why blocker 4 ("200+ direct ColumnArray casts") does not explode: 22 of 92 files in src/Functions/array/ are patched and the rest ride the framework normalization, as @alexey-milovidov predicted.

The cost is the mirror image. canBeInsideNullable now returns false for a type that demonstrably is inside Nullable. Every guard shaped like if (t->canBeInsideNullable()) that a Nullable(Array) value can actually reach has to be hand-patched with || isArray(t). The PR does this in about five places. Establishing that those are all the places is the main piece of evidence still missing, and it is the subject of the findings below.

Blocker-by-blocker

# Blocker What the PR does State
1 Stream-name collisions (two .null streams) New src/DataTypes/StructuredSubstreamNames.{h,cpp}: a parallel "structured" naming scheme with explicit .array path components, selected per column from the type. Legacy names stay byte-identical for every existing type. Addressed, and matches the RFC's candidate design
2 IFunction assumes Array results are never Nullable One opt-in virtual preserveNullableArrayResultForDefaultNulls, plus automatic emptying of array arguments on null rows and re-wrapping with the merged row null map Addressed, narrower than the RFC proposed
3 Pervasive canBeInsideNullable checks Predicate left unchanged; opt-in by construction (above) Addressed by design
4 200+ direct ColumnArray casts 22 array-function files patched; remainder handled by defaultImplementationForNulls Addressed by design
5 NullableSubcolumnCreator and .size0 nullability SerializationNullable::enumerateStreams installs the creator for arrays; all three NullableSubcolumnCreator::create overloads special-case Array. 04324 asserts a.size0 is Nullable(UInt64) Addressed and tested exactly as specified
6 Aggregate semantics AggregateFunctionNullBase::createResultType now takes arguments and returns Nullable(Array) where warranted; null arrays are skipped like any other null Addressed
7 Formats and schema inference Arrow, Arrow IPC, ORC, Parquet v3 and MsgPack readers, plus adjustNullableRecursively, all gated behind schema_inference_allow_nullable_array_type Addressed

Where the RFC has drifted from the implementation

@Avogar asked for an RFC, and #105192 is now stale in five places. Each is a decision this PR made but did not write back:

  1. Rollout. The RFC specifies Phases 0–6 as sequenced PRs (storage prototype, then framework, then function migration, then the gate, then formats, then stabilization). This PR does all six at once across 200 files.
  2. Function contract. The RFC proposes four framework capabilities. The implementation shipped one virtual with exactly one overrider (arrayElement, in is_null_mode). Simpler, and arguably better — but undocumented.
  3. arrayJoin. The RFC lists this as an open question. The PR resolved it: getArrayJoinDataType returns nullptr for nullable types, so ARRAY JOIN over Nullable(Array) throws TYPE_MISMATCH (asserted in 04266). That is a defensible "explicitly unsupported", but it is a semantic decision that should be recorded.
  4. Aggregates. The RFC's specific questions about groupArray and groupUniqArray are resolved implicitly by the combinator. I did not find a direct test for groupArray over a Nullable(Array) column.
  5. The audit deliverable. The RFC states that implementation "should not proceed until every entry is classified as covered-by-framework, manual change, explicitly unsupported, or no action required". That artifact does not exist yet.

Specific findings

1. unwrapNullableTuple in src/DataTypes/NestedUtils.cpp is the one site from the original review that is still untouched. For a Nullable(Tuple(..., Array(T), ...)), the Array element falls into the else branch and has its values replaced with [] at null positions. That is precisely the missing-versus-empty conflation this feature exists to remove, still live inside nullable tuples. This is a code-reading finding; I have not yet confirmed the reachable query shape.

2. makeNullableSafe silently degrades Nullable(Array) to Array. It returns the type unchanged when canBeInsideNullable is false, so the outer NULL is dropped with no exception. There are 32 call sites across 16 files; this PR touches 6 of those files. The remaining ten are:

src/Analyzer/Passes/ComparisonTupleEliminationPass.cpp
src/Analyzer/Passes/RewriteAggregateFunctionWithIfPass.cpp
src/Columns/ColumnNullable.h
src/Functions/FunctionDynamicAdaptor.cpp
src/Functions/FunctionNaiveBayesClassifier.cpp
src/Functions/FunctionVariantAdaptor.cpp
src/Functions/tupleToNameValuePairs.cpp
src/Interpreters/ExpressionAnalyzer.cpp
src/Storages/StorageMergeTreeIndex.cpp
src/TableFunctions/TableFunctionMergeTreeIndex.cpp

Each is a candidate for a silently wrong answer rather than an exception, so they are worth classifying explicitly even where the conclusion is "unreachable".

3. The dual naming dispatch is the sharpest edge in the PR, and it is not in the RFC. ISerialization::getFileNameForStream chooses structured versus legacy naming from settings.column_type when a type is available, and otherwise falls back to the path-only heuristic needsStructuredSubstreamNamesForPath. Two independent oracles have to agree for every type and path; where they disagree the result is a wrong file name, which surfaces as a missing stream or wrong data rather than an exception. The path-only arm exists to cover Dynamic/Object runtime variants and appears nowhere in #105192.

This is not hypothetical. Rebasing onto current master produces a conflict in MergeTreeReaderCompact::initSubcolumnsDeserializationOrder, where master's new check_stream_exists_callback resolves names through the untyped getFileNameForStream overload. Taking master's side verbatim compiles and looks correct, but lands on the path-only arm for exactly the columns this PR introduces. The callback needs the part's stored column type.

4. getPathPrefixInRange in StructuredSubstreamNames.cpp duplicates the substream-to-name switch from getNameForSubstreamPath. Object/JSON substream types are being added to master continuously, and a duplicated switch will drift silently. One source of truth would be safer.

5. Minor: in ArrayJoinResultIterator::next, the removeNullable call and the ColumnNullable unwrap appear to be unreachable, because the enclosing getArrayJoinDataType already returns nullptr for every nullable type. Harmless today, but it suggests either the guard or the unwrap is not what was intended.

On the rebase

The PR is currently CONFLICTING; roughly 3400 commits have landed on master since the last merge. I resolved it locally to confirm the findings above against current master. Beyond the four conflicts already noted, master has since added a fifth in src/Functions/array/arrayFold.cpp, and three things are silently dropped rather than conflicting:

  • All three documentation changes target the pre-move docs/en/... layout. master now has docs/reference/interfaces/specs/NativeFormat.mdx, docs/reference/data-types/array.mdx and docs/reference/data-types/nullable.mdx, and the new files use the <Info> component rather than ::::note. Without re-porting, those three edits vanish with no conflict marker.
  • schema_inference_allow_nullable_array_type needs adding to the Arrow and ArrowStream schema-cache keys in ArrowIPC/ArrowIPCBlockInputFormat.cpp, as noted earlier in this thread.
  • tests/queries/0_stateless/04235_04235_nullable_array_nested_nullable.reference is a zero-byte orphan with an accidentally doubled number prefix and no matching query file.

@zhanglistar — thank you for the sustained work here; the test suite in particular is substantial. Maintainer edits appear to be disabled on the bigo-sg/ClickHouse fork, so I cannot push the rebase to your branch directly. I am happy to publish the rebased branch somewhere you can pull from, or to walk through the resolutions, whichever is more useful. Are you still able to continue driving this?

@yakov-olkhovskiy

yakov-olkhovskiy commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

🕵

Proposed plan to move forward

Following on from the assessment above. The functionality is essentially there; what is missing is the evidence needed to approve a change that alters an on-disk format. The steps below are ordered so that the irreversible decisions get scrutiny before merge and the reversible ones can follow.

Step 1 — Get the branch back onto master

Mechanical, but it is the current hard blocker and the drift grows daily. Five conflicts, plus the three silent losses listed in the assessment (docs re-port, Arrow schema-cache keys, orphaned reference file), plus the no-fasttest tag on 04615 that was the single CI failure in the last full run.

Two resolutions in that merge are semantic rather than mechanical and should be reviewed rather than taken on faith:

  • AlterCommands.cpp: master's columnsAddedByAlter flatten-nested expansion has to be fed final_data_type, not command.data_type, or the resolved NULL/NOT NULL modifier is lost.
  • MergeTreeReaderCompact.cpp: master's new check_stream_exists_callback must resolve stream names from the part's stored column type, not the bare column name, for the reason given in finding 3.

I have this done locally and validated against a build. Since maintainer edits are disabled on the fork, I can publish the branch for @zhanglistar to pull, or open it as a separate PR — whichever the author prefers.

Step 2 — Produce the audit the RFC asks for

This is the highest-value remaining work and the thing most likely to unblock approval, because it converts "we believe the opt-in design contains the blast radius" into a checkable claim.

The design in this PR makes the audit tractable in a way that flipping canBeInsideNullable never would have. The question is not "are 70 files correct" but the much narrower: which call sites can a Nullable(Array) value actually reach, and of those, which need || isArray? Three families to enumerate and classify:

  • canBeInsideNullable — 105 call sites
  • makeNullableSafe and the rest of the makeNullable* family — the silent-degradation vector from finding 2
  • direct ColumnArray and DataTypeArray casts — the ones not already covered by framework normalization

Each site classified as one of: covered by framework, needs || isArray, explicitly unsupported, or no action required. Fix whatever the pass turns up, starting with NestedUtils.cpp. The resulting table belongs on #105192, which is where it was promised.

Step 3 — Review the storage format before merge, not after

Everything else in this PR is a normal bug-fix cycle. Stream naming is not: once parts exist in the wild with structured names, the scheme is permanent. Three concrete items:

  1. A test asserting that both dispatch arms — type-based and path-based — agree for every type and substream path they can both see. Right now nothing enforces that invariant, and a disagreement produces wrong data rather than an exception.
  2. An audit of every getFileNameForStream caller for which arm it lands on, and whether the type is available where it matters. The MergeTreeReaderCompact conflict shows this is easy to get wrong even when the code reads naturally.
  3. Collapse the duplicated substream-to-name switch (finding 4) to a single source of truth, so new Object/JSON substream types cannot drift between the two schemes.

Old-part reads, merges, mutations and ALTER paths should be covered explicitly in the same pass.

Step 4 — Reconcile #105192 with what was built

An RFC was requested, and a stale one is worse than none. The five drift items from the assessment need writing back: the makeNullableAllowingArray opt-in design in place of the naming-mode sketch, the single-virtual function contract, ARRAY JOIN as explicitly unsupported, the aggregate resolution, and the path-only dispatch arm that the RFC never described.

Step 5 — Plan for the tail

The Nullable(Tuple) precedent is the honest guide here: months of corner-case fixes after merge, as @alexey-milovidov noted in this thread. That is not an argument against merging — CI and fuzzing coverage are much stronger now than they were then — but it should be expected and staffed rather than treated as a surprise. Fuzzer coverage for the new type, the Nullable(Map) question the RFC deliberately deferred, and filling out the coverage matrix all belong here.

On splitting the PR

Worth naming explicitly, since it is the obvious question for a 200-file, ~6700-line change that touches an on-disk format.

Splitting along the RFC's own phase lines (storage naming, then framework, then functions, then formats) would make each piece independently reviewable. Against that: it costs the author substantial rework, and the PR is currently green but for one tag, so the risk of losing that state is real.

My suggestion is not to split, and to buy reviewer confidence instead through Step 2 and Step 3 item 1 — a complete call-site classification and an enforced invariant on the naming dispatch address the actual review risk more directly than four smaller PRs would. But this is a maintainer call rather than mine alone, and I would rather raise it now than after another rebase cycle.

I am happy to take on Steps 1 through 3 directly. @zhanglistar, if you are still active on this, I would rather work alongside you than around you — let me know how you would like to divide it.

@yakov-olkhovskiy

yakov-olkhovskiy commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

🕵

Rebase validated, plus one confirmed defect

Follow-up to the two comments above, now that the rebase onto current master builds and runs.

Validation status

  • Builds clean (Debug, clang-21).
  • Stateless: 47/47 pass — every *nullable_array* test in the suite.
  • Unit: 28/28 pass — ColumnNullable, NullableArraySerialization and StructuredSubstreamNames.

A sixth merge site that git does not flag

Beyond the four conflicts noted earlier in this thread and the fifth in arrayFold.cpp, there is a sixth: src/Storages/MergeTree/MergeTreeDataPartWide.cpp. git merge reports it as auto-merged with no conflict, but the result does not compile — nine errors across two call sites.

This branch changes getStreamNameForColumn to the NameAndTypePair overload so the naming scheme is chosen from the column's type, obtaining the pair from a columns member. master has since restructured both sites: the accessor is now getColumns, and removeMarksFromCache became a forEach lambda, so the continue there is no longer inside a loop.

Worth flagging beyond the mechanical fix: this failed loudly only because columns happened not to resolve. The same class of structural drift in a context where the identifier did resolve would have compiled silently. Conflict-marker triage is not sufficient for this rebase.

Finding 1 is confirmed, and the interesting case is not the one I described

I posted unwrapNullableTuple as a code-reading finding with the reachable query shape unconfirmed. It reproduces. Given an Arrow file holding Array(Nullable(Tuple(x Array(Int32)))) whose second element is NULL:

SET allow_experimental_nullable_array_type = 1;

-- default read, tuple stays nullable
SELECT a FROM file('nt.arrow', Arrow);
-- [([1,2]),NULL]                                    correct

-- non-nullable tuple hint, forces unwrapNullableTuple
SELECT a FROM file('nt.arrow', Arrow, 'a Array(Tuple(x Array(Int32)))');
-- [([1,2]),([])]                                    expected

-- x explicitly hinted as Nullable(Array)
SELECT a FROM file('nt.arrow', Arrow, 'a Array(Tuple(x Nullable(Array(Int32))))');
-- [([1,2]),([])]                                    wrong

The third case is the defect. The user explicitly requests Nullable(Array(Int32)), the experimental setting is enabled, and the hint is honored at the type level — toTypeName returns Array(Tuple(x Nullable(Array(Int32)))) — but the value for the null struct comes back as [] with isNull() = 0. The column can represent the distinction, the user asked for it, and it is still silently flattened to an empty array.

The mechanism is NestedUtils.cpp:172: the branch tests elem_type->canBeInsideNullable(), which is false for Array by design, so the array field takes the default-substitution path before the hinted type is applied. It is reachable from the ORC, Arrow and Arrow IPC readers whenever a nullable struct sits inside a list.

To be precise about severity: this is not a regression. With the gate off, the same hint is rejected with ILLEGAL_TYPE_OF_ARGUMENT, so this is new gated surface that does not yet do what it says, rather than a break in existing behaviour. But it is the missing-versus-empty conflation this feature exists to eliminate, occurring inside the feature itself, so it seems worth fixing before the gate is widened.

Why this supports doing the audit before merge

This came out of chasing a single canBeInsideNullable call site — the one site from the original review list that this PR had not touched. That is one site out of 105, in one of the three families listed in the plan comment. It is a reasonable argument that the remaining classification pass is worth completing before merge rather than after.

One related observation from the unit tests: StructuredSubstreamNames.UsesStructuredWhenColumnTypeSet and StructuredSubstreamNames.UsesLegacyWithoutColumnType each pin one arm of the naming dispatch, which is good. Nothing yet asserts that the two arms agree for the type and path combinations both can see, which is the invariant that actually protects the on-disk format.

Happy to open the fix for unwrapNullableTuple as a separate small PR against master if that is easier to review independently, or to fold it in here.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Superseded by #115165. I could not push the conflict resolution to the external fork because maintainer edits are disabled; the new PR preserves the original implementation and credits @zhanglistar. Thank you for the contribution.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Superseded by #115165. I could not push the conflict resolution to the external fork because maintainer edits are disabled; the new PR preserves the original implementation and credits @zhanglistar. Thank you for the contribution.

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 manual approve Manual approve required to run CI pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants