Skip to content

Fix server abort for non-nullable LowCardinality tuple-element sort key - #108679

Merged
Avogar merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105356-carrier3-nonnullable-lc
Jul 14, 2026
Merged

Avogar merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105356-carrier3-nonnullable-lc

Conversation

@groeneai

@groeneai groeneai commented Jun 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #105356
Related: #102942

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

Fixed a server abort (Sort order of blocks violated) during a merge, and incorrect reads, when a non-nullable LowCardinality element of a Nullable(Tuple(...)) column is used as a subcolumn (for example as a sort key).

Description

Residual carrier of #105356 that #102942 (merged) does not cover. Carriers 1 (Nullable(Decimal)) and 2 (LowCardinality(Nullable(String))) are fixed there; a non-nullable LowCardinality(String) element was still mishandled.

Repro on current master (debug), git hash 07643905aae, report shape from issue #105356:

SET allow_experimental_nullable_tuple_type = 1;
CREATE TABLE t (c0 Nullable(Tuple(String, LowCardinality(String))), c2 Decimal)
ENGINE = SummingMergeTree() ORDER BY (`c0.2`, c2)
SETTINGS allow_nullable_key = 1, index_granularity = 1;
INSERT INTO t SELECT if(number % 2 = 0, NULL, ('a', toLowCardinality('p'))), toDecimal32(number, 0) FROM numbers(4);
INSERT INTO t SELECT if(number % 2 = 0, NULL, ('b', toLowCardinality('q'))), toDecimal32(number + 10, 0) FROM numbers(4);
OPTIMIZE TABLE t FINAL;  -- Logical error: 'Sort order of blocks violated for column number 1, left: 'p', right: ''.'

Such an element reaches NullableSubcolumnCreator::create as a ColumnLowCardinality whose dictionary is not nullable, so both canExtractedSubcolumnsBeInsideNullable and canContainNull are false. None of the three create overloads applied the outer tuple null map, so the extracted subcolumn dropped the outer NULLs entirely.

The extracted subcolumn type is promoted to LowCardinality(Nullable(T)) so it can represent the outer NULLs. All three creator overloads are now made consistent with that type:

  • Type (create(DataTypePtr)): promote the non-nullable LowCardinality(T) to LowCardinality(Nullable(T)) via the existing makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe.
  • In-memory column (create(ColumnPtr)): promote the column with cloneNullable() and fold in the outer null map. This fixes the merge abort, where the in-memory sort key was re-extracted and exposed the inner dictionary value for outer-NULL rows, contradicting the on-disk sort key and tripping CheckSortedTransform.
  • Read path (create(SerializationPtr)): wrap the original (non-nullable) LowCardinality serialization in SerializationNullableWithParentNullMap, keeping the on-disk stream layout unchanged. applyParentNullMapToExtractedSubcolumn promotes the read LowCardinality(T) column to LowCardinality(Nullable(T)) (rebuilding the dictionary with a NULL placeholder and remapping indexes) before folding in the outer null map. The promotion runs before the no-NULL-rows early-out so the column type is consistent across all read ranges.

Without the read-path part, reading the subcolumn directly from a part (SELECT c0.2) produced a ColumnLowCardinality with a non-nullable dictionary while its declared type was LowCardinality(Nullable(T)): isNull(c0.2) then aborted with ColumnUnique can't contain null values, and outer-NULL rows leaked the inner dictionary value instead of reading NULL. With the fix, the subcolumn reads NULL for outer-NULL rows on both wide and compact parts.

Other carriers (ColumnNullable, LowCardinality(Nullable), Dynamic, Variant) are unchanged. The 04338/04339 tests are extended to cover reading the subcolumn directly (value and isNull) from both wide and compact parts; both tests fail on master and pass with this change.

Follow-up: tupleElement consistency (@Avogar review)

The same inconsistency existed on the tupleElement function path. It inherited the default LowCardinality implementation, whose convertLowCardinalityColumnsToFull -> recursiveRemoveLowCardinality recurses into the tuple and strips a nested LowCardinality(...) element before getReturnTypeImpl/executeImpl run. So t.a (subcolumn) kept LowCardinality(...) while tupleElement(t, 'a') returned String / Nullable(String), and a LowCardinality(Nullable(String)) element was downgraded to Nullable(String):

SELECT t.a, toTypeName(t.a), tupleElement(t, 'a'), toTypeName(tupleElement(t, 'a')) FROM test;

useDefaultImplementationForLowCardinalityColumns() is now disabled for tupleElement, and both its return type and its Nullable(Tuple(...)) null-map folding are routed through the same helpers the subcolumn path uses (makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe and NullableSubcolumnCreator). The function now produces a (type, column) pair identical to the subcolumn reader for every element type. New test 04344_tuple_element_lowcardinality_consistency forces the non-optimized path via materialize(t) and asserts type+value equality across the subcolumn path, the optimized function path, and the materialized path (plain LowCardinality, LowCardinality(Nullable), String, Map elements); it fails on HEAD before this change and passes after.

Version info

  • Merged into: 26.7.1.941 (included in 26.7 and later)

A non-nullable LowCardinality(T) element of Nullable(Tuple(..., LowCardinality(T), ...))
used as a sort key aborted the server with "Sort order of blocks violated" during a
horizontal merge (OPTIMIZE FINAL).

Such an element reaches NullableSubcolumnCreator::create as a ColumnLowCardinality whose
dictionary is not nullable, so both canExtractedSubcolumnsBeInsideNullable and
canContainNull are false. Neither create overload applied the outer tuple null map, so the
in-memory sort key re-extracted during the merge exposed the inner dictionary value for
rows whose outer tuple was NULL. That contradicted the on-disk sort key (which combined
both masks), and the next merge tripped CheckSortedTransform.

The type creator now promotes such an element to LowCardinality(Nullable(T)) (reusing
makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe), and the column creator
promotes the ColumnLowCardinality with cloneNullable() before folding in the outer mask via
applyParentNullMapToExtractedSubcolumn, so the extracted (type, column) pair stays
consistent and can represent the outer NULLs. Other carriers (ColumnNullable,
LowCardinality(Nullable), Dynamic, Variant) are unchanged.

Extends 04339_105356_nullable_tuple_subcolumn_sort_order with the non-nullable LC carrier.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. OPTIMIZE TABLE t FINAL on the schema in the description aborts the server every time on current master (debug, git 07643905aae, Build ID 28ec452353f0). Requires distinct non-null inner LC values across the two parts ('p'/'q') plus varying c2 so the merge compares cross-part sort keys.
b Root cause explained? A non-nullable LowCardinality(String) tuple element reaches NullableSubcolumnCreator::create as a ColumnLowCardinality with a non-nullable dictionary, so canExtractedSubcolumnsBeInsideNullable and canContainNull are both false. Neither overload applied the outer tuple null map -> the in-memory sort key re-extracted during the merge exposed the inner dictionary value for outer-NULL rows -> it disagreed with the on-disk sort key (which combines both masks) -> CheckSortedTransform raised the LOGICAL_ERROR and abort()ed the server.
c Fix matches root cause? Yes. The type creator promotes the element to LowCardinality(Nullable(T)) and the column creator promotes the column with cloneNullable() before folding in the outer mask, so the extracted (type, column) pair can represent the outer NULLs. This is exactly the dropped-mask mechanism from (b), not a symptom guard.
d Test intent preserved / new tests added? Existing 04339 carriers 1 and 2 unchanged. Added carrier 3 (non-nullable LC) to the same test, asserting the merge completes (count()>0, uniqExact(_part)) and the extracted subcolumn type is now LowCardinality(Nullable(String)).
e Both directions demonstrated? Yes. Extended 04339 FAILS on clean master (server aborts at carrier-3 OPTIMIZE FINAL; Build ID 28ec452353f0) and PASSES with the fix (Build ID 4594d4e36779). Verified by rebuilding clean (Build ID returned to 28ec452353f0 exactly), reproducing the abort, then restoring the fix.
f Fix is general across code paths? Both create(DataTypePtr) and create(ColumnPtr) are fixed and kept consistent (type promotes to LC(Nullable(T)); column promotes the same way). Other carriers (ColumnNullable, LowCardinality(Nullable), Dynamic, Variant) hit the existing canContainNull branch and are untouched.
g Fix generalizes across inputs (params/datatypes/wrappers)? Verified across the LC inner-type and outer-mask matrix: LowCardinality(String) and LowCardinality(FixedString(2)) both promote correctly and survive merge; all-NULL, all-non-null, and mixed outer masks all work; the sibling LowCardinality(Nullable(String)) carrier-2 type is unchanged.
h Backward compatible? Yes. On-disk format unchanged. The change only affects the in-memory extracted-subcolumn (type, column) for the non-nullable LC carrier, which previously aborted the merge; no setting default or wire/disk format changes.
i Invariants and contracts preserved? Yes. The fix restores the block-structure invariant CheckSortedTransform enforces: the in-memory sort key now matches the on-disk sort key (both apply the outer null map). cloneNullable() yields a LowCardinality(Nullable(T)) whose nullable dictionary applyParentNullMapToExtractedSubcolumn requires. The (type, column) pair returned by the two overloads is consistent by construction.

Known separate gap (flagged in the PR description, not addressed here): the on-disk SELECT read path of this subcolumn does not apply the outer null map (pre-existing; not a regression of this change). Build ID of the validated fixed binary: 4594d4e3677965cecb902595d110c456d0fd8a5a.

Session id: cron:clickhouse-worker-slot-2:20260627-045100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @CurtizJ -- could you review this? It is the residual carrier-3 of #105356 that #102942 did not cover: a non-nullable LowCardinality(String) element of Nullable(Tuple(...)) used as a sort key aborted the server during merge because NullableSubcolumnCreator dropped the outer null map. The fix promotes such an element to LowCardinality(Nullable(T)) in both the type and column creators before folding in the outer mask.

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

clickhouse-gh Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a0df6fb]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
04402_map_functions_lowcardinality FAIL cidb IGNORED
Stress test (arm_release) FAIL
Cannot start clickhouse-server FAIL cidb IGNORED
Logical error: Stream A for column B with type C is not found (STID: 3190-62c4) FAIL cidb IGNORED
Check failed FAIL cidb IGNORED

AI Review

Summary

This PR fixes the remaining Nullable(Tuple(...)) + non-nullable LowCardinality(...) carrier in NullableSubcolumnCreator, extends the fix to the direct read path, and makes tupleElement preserve LowCardinality consistently while restoring default-filling for element types that cannot represent NULL. I re-checked the current code against the prior review discussion and did not find a remaining correctness, compatibility, or test-gap issue that needs a new review comment.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 27, 2026
…ad path too

The non-nullable LowCardinality(T) element of Nullable(Tuple(..., LowCardinality(T), ...))
has its extracted subcolumn type promoted to LowCardinality(Nullable(T)) so it can carry the
outer tuple's NULLs (fixing the OPTIMIZE FINAL "Sort order of blocks violated" abort). The
in-memory column creator promoted the column to match, but the serialization (read) path did
not: reading the subcolumn directly from a MergeTree part produced a ColumnLowCardinality with
a non-nullable dictionary while its declared type was LowCardinality(Nullable(T)). That
(type, column) mismatch made isNull() on the subcolumn abort with
"ColumnUnique can't contain null values", and outer-NULL rows leaked the inner dictionary value.

Wrap the original (non-nullable) LowCardinality serialization in
SerializationNullableWithParentNullMap so the on-disk stream layout is unchanged, and promote
the read column to LowCardinality(Nullable(T)) in applyParentNullMapToExtractedSubcolumn before
folding in the outer null map. The promotion happens before the no-NULL-rows early-out so the
column type stays consistent across all read ranges.

Extend the 04338 / 04339 tests to cover reading the subcolumn directly (value + isNull) from
both wide and compact parts.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. OPTIMIZE TABLE t FINAL on the body's repro aborts every time with Sort order of blocks violated; SELECT isNull(\c0.2`)over a MergeTree part aborts every time withColumnUnique can't contain null values`.
b Root cause explained? Yes. A non-nullable LowCardinality(T) element of Nullable(Tuple(...)) fails both canExtractedSubcolumnsBeInsideNullable and canContainNull, so the subcolumn creator dropped the outer null map. The type is promoted to LowCardinality(Nullable(T)), but the column (in-memory and on read) kept a non-nullable dictionary, so the (type, column) pair was inconsistent: the merge re-extracted a sort key that leaked the inner value for outer-NULL rows (contradicting the on-disk key, tripping CheckSortedTransform), and direct reads aborted isNull / leaked the value.
c Fix matches root cause? Yes. All three NullableSubcolumnCreator::create overloads are made consistent with the promoted type: type -> LowCardinality(Nullable(T)); in-memory column -> cloneNullable() + outer mask; read path -> wrap original serialization + promote the read column before applying the outer mask. No symptom guard.
d Test intent preserved / new tests added? Yes. No assertion weakened. 04339 extended with a read-path block (value + isNull on wide and compact parts); 04338 t_lc_plain reference + comment updated to the now-correct promoted output.
e Both directions demonstrated? Yes. 04338 and 04339 both FAIL on clean master (build 28ec452353f0) and PASS with the fix (build 9971a2329ea4); 20/20 stable runs.
f Fix general across code paths? Yes. The bug spans all three subcolumn-creator overloads (type, in-memory column, read serialization); each is fixed. Sibling carriers (ColumnNullable, LowCardinality(Nullable), Dynamic, Variant) already route through the existing branch and are unchanged. Not a symptom guard: the (type, column) consistency is restored at the source.
g Generalizes across inputs (params/datatypes/wrappers)? Yes. Verified LowCardinality(String) and LowCardinality(FixedString(2)); wide and compact parts; multi-granule reads (multiple ranges); all-NULL part, all-non-null part, and mixed. LowCardinality(Nullable(...)) (already nullable) is correctly skipped (no double-promotion).
h Backward compatible? Yes. No setting default, on-disk format, or wire format change. On-disk LC stream layout is unchanged (the read path wraps the original serialization); the change only affects the in-memory representation of an extracted subcolumn of an experimental Nullable(Tuple).
i Invariants and contracts preserved? Yes. The promotion uses compactInplaceToNullable() (already used by cloneNullable()), which rebuilds the dictionary with a NULL placeholder AND remaps indexes, so dictionary/index invariants hold. The promotion runs before the no-NULL-rows early-out, keeping the column type consistent across every read range. applyNegatedNullMap's nestedIsNullable() precondition is satisfied because the column is promoted first.

Session id: cron:clickhouse-worker-slot-3:20260627-170900

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 7850d5934ee: the Fast test failure on 04338 flagged a real gap, so this PR now also fixes the read path (not just the merge).

The previous revision promoted the subcolumn type to LowCardinality(Nullable(T)) but left create(SerializationPtr) unpromoted, so reading the subcolumn directly from a part produced a non-nullable dictionary under that nullable type: isNull(c0.2) aborted with ColumnUnique can't contain null values and outer-NULL rows leaked the inner value. The read path now wraps the original LC serialization and promotes the read column before applying the outer null map, so on-disk streams are unchanged and reads return NULL correctly on wide and compact parts. 04338/04339 updated and extended accordingly (both fail on master, pass here).

@groeneai

groeneai commented Jun 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7850d59

CI is fully finished (Finish Workflow green). Every failure below has an owner: a fixing PR (ours 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
Fast test / 04338_tuple_inside_nullable_null_carrying_elements PR-caused (.reference + stale comment drift after the read-path fix) Fixed in this PR @ 7850d59 (Fast test now green)
AST fuzzer (amd_debug, targeted, old_compatibility) / Bad cast ColumnString to ColumnLowCardinality (STID 4525-5f05) pre-existing trunk fuzzer finding (1 master hit 2026-06-13 + 9 distinct PRs/30d; unrelated to this PR's NullableUtils.cpp change; query is a Variant(Int256, LowCardinality(String)) IN-subquery) #107773 (external, open), Avogar's convertToFullIfNeeded recursive-LowCardinality-stripping refactor
Stateless tests (amd_tsan, parallel, 2/2) / 03209_parallel_replicas_lost_decimal_conversion transient flaky (CI rerun 49/49 passed; 0 master, 3 PRs/30d; unrelated to this PR) a fix task is created (investigating at full effort; fixing-PR link to follow here)
CH Inc sync n/a CH Inc sync (private, not actionable by us)

Mergeable Check / PR are aggregator rows reflecting the two reds above; neither is PR-caused.

Session id: cron:our-pr-ci-monitor:20260627-220000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Update on the 03209_parallel_replicas_lost_decimal_conversion ledger line (Stateless tests amd_tsan, parallel, 2/2).

Investigated at full effort. The failure is a transient ALL_CONNECTION_TRIES_FAILED (Code 279, a handled exception) raised in ParallelReplicasReadingCoordinator::markReplicaAsUnavailable while establishing the connection to the localhost parallel_replicas cluster, before the decimal-conversion query runs. Evidence it is environmental, not a defect in this test or the decimal path:

  • 0 failures across 10,258 master runs in the last 30 days.
  • CI's own diagnostic rerun passed 49/49 immediately.
  • Shared transient signature: in 30 days, ALL_CONNECTION_TRIES_FAILED on amd_tsan stateless hit 5 unrelated connection-heavy tests (01119_session_log, 02345_implicit_transaction, 02590_interserver_mode_client_info_initial_query_start_time, 03603_reading_s3_cluster_all_nodes_unavailable, 03209), 15 rows total, 0 on master.

The failure precedes any randomized-setting-dependent logic (connection establishment under TSan scheduling pressure), so there is no setting to pin and no test-logic or decimal-conversion defect, and it is not reproducible. No per-test code change is warranted; a fresh run of this job clears it. Closing this line as not actionable.

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

I would do it differently, let's change canExtractedSubcolumnsBeInsideNullable so it returns true if type is LC and can be transformed to LC(Nullable). And call makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe instead of makeNullableSafe when needed

Comment thread src/DataTypes/NullableUtils.cpp Outdated
Comment on lines +180 to +186
if (canExtractedSubcolumnsBeInsideNullable(prev))
return makeNullableSafe(prev);

/// A non-nullable `LowCardinality(T)` cannot be wrapped in `Nullable`, but it must still be able to
/// represent the outer column's NULLs, so promote it to `LowCardinality(Nullable(T))`. For every other
/// type this returns `prev` unchanged, matching the previous behaviour.
return makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe(prev);

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.

Why not to use just return makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe(prev), won't it be the same?

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.

Yes, exactly the same. Done in fc15065.

Address review feedback: create(DataTypePtr) now calls
makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe directly. This is
exactly equivalent to the previous two-branch form (a promotable non-LC type
takes the makeNullableSafe path inside the helper; a non-nullable
LowCardinality(T) is promoted to LowCardinality(Nullable(T)); anything else is
returned unchanged), just less code.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Simplified create(DataTypePtr) to a single makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe(prev) call in fc15065.

On the other part of the suggestion, changing canExtractedSubcolumnsBeInsideNullable itself to return true for a promotable LC: I left it as-is on purpose. That predicate has callers that read "true" as "wrap in plain Nullable(...)" rather than "promote to LowCardinality(Nullable(T))": tupleElement.cpp (std::make_shared<DataTypeNullable>(element_type) and ColumnNullable::create(res, ...)), SerializationVariant.cpp, and DataTypeDynamic.cpp. Making it true for LC would route those into Nullable(LowCardinality(...)), which is the wrong wrapping. The LC case is already captured by the dedicated canExtractedSubcolumnsBeInsideNullableOrLowCardinalityNullable predicate and the ...OrLowCardinalityNullableSafe maker, which is exactly what the simplified call now uses. If you'd prefer I still fold this into the shared predicate (e.g. with a separate LC-aware overload), happy to.

Comment thread src/DataTypes/NullableUtils.cpp Resolved
…ty elements

tupleElement inherited the default LowCardinality implementation, which
strips a nested LowCardinality(...) tuple element via recursiveRemoveLowCardinality
before extraction. As a result tupleElement(t, 'a') returned String /
Nullable(String) while the subcolumn path t.a returned LowCardinality(String) /
LowCardinality(Nullable(String)) for the same element, and a
LowCardinality(Nullable(String)) element was silently downgraded to
Nullable(String).

Disable useDefaultImplementationForLowCardinalityColumns for tupleElement so
the element type is preserved, and route the Nullable(Tuple(...)) null-map
folding through the same helpers as the subcolumn path:
makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe for the return type
and NullableSubcolumnCreator for the column. This guarantees the (type, column)
pair produced by the function matches the subcolumn reader for every element
type, including the non-optimized path (materialize(t)).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Done in 236b1ab. tupleElement now matches the subcolumn path for LowCardinality elements.

Root cause: tupleElement inherited the default LowCardinality implementation, whose convertLowCardinalityColumnsToFull -> recursiveRemoveLowCardinality recurses into the tuple and strips a nested LowCardinality(...) element before getReturnTypeImpl/executeImpl run. So t.a (subcolumn) kept LowCardinality(...) while tupleElement(t, 'a') did not, and a LowCardinality(Nullable(String)) element was even downgraded to Nullable(String).

Fix: disable useDefaultImplementationForLowCardinalityColumns() for tupleElement and route the return type and the Nullable(Tuple(...)) null-map folding through the same helpers the subcolumn path uses (makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe + NullableSubcolumnCreator). Your query now returns matching types on both columns:

select t.a, toTypeName(t.a), tupleElement(t, 'a'), toTypeName(tupleElement(t, 'a')) from test

both LowCardinality(Nullable(String)), NULLs preserved.

New test 04344_tuple_element_lowcardinality_consistency forces the non-optimized path with materialize(t) and asserts type+value equality across the subcolumn path, the optimized function path, and the materialized path, for plain LowCardinality, LowCardinality(Nullable), plain String, and Map elements. It fails on HEAD before the fix and passes after.

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT toTypeName(tupleElement(t,'a')) FROM test on Tuple(a LowCardinality(String), b UInt32) deterministically returns String on HEAD (expected LowCardinality(String)); tupleElement(materialize(t),'a') on Nullable(Tuple(a LowCardinality(String),...)) returns Nullable(String) (expected LowCardinality(Nullable(String))).
b Root cause explained? tupleElement inherited useDefaultImplementationForLowCardinalityColumns()=true. The framework's convertLowCardinalityColumnsToFull -> recursiveRemoveLowCardinality recurses into the tuple and strips a nested LowCardinality(...) element before getReturnTypeImpl/executeImpl run, so the extracted element lost its LowCardinality wrapper while the subcolumn path (t.a, via NullableSubcolumnCreator) kept it.
c Fix matches root cause? Yes. Disable the default LC implementation for tupleElement (element type preserved), and route the return type and the Nullable(Tuple) null-map folding through the exact same helpers as the subcolumn path (makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe + NullableSubcolumnCreator).
d Test intent preserved / new tests added? New test 04344_tuple_element_lowcardinality_consistency added, asserting (type, value) equality across the subcolumn path, the optimized function path, and the materialize() non-optimized path. Existing 03289/04056/04051/04207/04338/04339 still pass.
e Both directions demonstrated? Yes. 04344 FAILS on the pristine (pre-fix) rebuild (build id 8a3d66..) and PASSES on the fixed rebuild (build id 30501602..), including 10/10 runs with randomization.
f Fix is general across code paths? Yes. The single Nullable(Tuple) extraction site now delegates to NullableSubcolumnCreator, which is the SAME code the subcolumn reader uses, so the function and subcolumn paths cannot diverge again. No sibling tupleElement extraction path exists. Not a symptom guard.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified type+value consistency across String, LowCardinality(String), LowCardinality(Nullable(String)), Nullable(Decimal), and Map(String,String) elements, with plain and Nullable(Tuple) outer types, element-own-NULL + outer-NULL (OR semantics preserved), and both enable_analyzer modes. Map correctly stays Map(...) (cannot be Nullable) and reads {} for outer-NULL rows on every path (unchanged).
h Backward compatible? (maintainer-approved exception only) The type change is the requested consistency fix (@Avogar). tupleElement(t,'a') on a LowCardinality element now returns LowCardinality(...) matching the subcolumn t.a; this is a bug fix (the paths disagreed and LC(Nullable) was silently downgraded), no on-disk/wire format change, no setting default change.
i Invariants and contracts preserved? Yes. NullableSubcolumnCreator::create(ColumnPtr) uses applyNegatedNullMap (OR of outer null map into any existing element null map), matching the previous mergeNullMaps OR semantics; element-own NULLs are preserved. Column size and null-map length invariants hold. The removed mergeNullMaps helper and now-unused LOGICAL_ERROR error code were dropped to avoid unused-symbol warnings.

Session id: cron:clickhouse-worker-slot-4:20260707-184200

Comment thread src/Functions/tupleElement.cpp Resolved
The tupleElement consistency refactor routed the Nullable(Tuple(...)) null-map
folding through NullableSubcolumnCreator::create for every element type. For an
element that can neither be wrapped in Nullable nor carry NULL itself (Map,
Array), that helper returns the column unchanged, so outer-NULL rows leaked
whatever payload happened to sit under the null map in the hidden nested column
instead of reading the element default.

Restore explicit default-filling for the non-null-capable / non-LC-promotable
case, matching NestedUtils::unwrapNullableTuple and the stored subcolumn, and
keep the NullableSubcolumnCreator path (LowCardinality(Nullable) promotion and
null-map OR-ing) for element types that can represent NULL. Extend
04344_tuple_element_lowcardinality_consistency with materialize()-forced Map and
Array regressions whose hidden payload under outer NULL is non-default.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.80% -0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 46/46 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a0df6fb

CI fully finished (Finish Workflow SUCCESS). Every failure below has an owner (a fixing PR). None PR-caused.

Check / test Reason Owner / fixing PR
Stateless (arm_asan_ubsan, targeted) / 04402_map_functions_lowcardinality flaky (randomized bucketed Map serialization key order; 2 master + 10 PRs/30d, unrelated to this diff) #108677 (ours, open, approved)
Stress test (arm_release) / Logical error "Stream ... is not found" (STID 3190-62c4) trunk bug (Dynamic/Variant merge missing variant_discr stream, issue #107561; 4 unrelated PRs/30d) #107562 (external, open)
Stress test (arm_release) / Cannot start clickhouse-server, Check failed stress cascade from the STID 3190-62c4 fatal above #107562 (external, open)
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260708-023000

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a0df6fb1ea562036089071688bd050e823402a

Every failure below has an owner: a fixing PR (ours 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. None are caused by this PR (diff touches only src/Functions/tupleElement.cpp + one test).

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, targeted) / 04402_map_functions_lowcardinality flaky (randomized bucketed Map serialization key order) #108677 (ours, open)
AST fuzzer (amd_debug, targeted) / Bad cast ColumnNullable→ColumnString (STID 2575-3c75), minOrDefault(*) over GROUPING SETS + group_by_use_nulls trunk (SingleValueDataString MinMax, issue #91119 family) #104350 (ours, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / arrayFold non-const LowCardinality plus type mismatch (STID 2735-550f) trunk (arrayFold LC column/type divergence) #109462 (ours, open)
Stress test (arm_release) / Stream .variant_discr for Dynamic column not found (STID 3190-62c4) trunk (Variant/Dynamic subcolumn serialization) #107562 (external, open) — issue #107561
Stress test (arm_release) / Cannot start clickhouse-server + Check failed crash collateral of STID 3190-62c4 above #107562 (external, open)
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260708-030000

@Avogar
Avogar added this pull request to the merge queue Jul 14, 2026
Merged via the queue into ClickHouse:master with commit 10a8947 Jul 14, 2026
171 of 174 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 14, 2026
pull Bot pushed a commit to infdahai/ClickHouse that referenced this pull request Jul 30, 2026
…entation

An extracted subcolumn of a Nullable(Tuple(...)) column whose element is a
non-nullable LowCardinality(T) has its type promoted to
LowCardinality(Nullable(T)) so that it can carry the parent's NULLs. On a Compact
part MergeTreeReaderCompact therefore creates the result column already promoted,
and SerializationNullableWithParentNullMap built its per-range deserialization
buffer from it. The nested SerializationLowCardinality deserializes into that
nullable-dictionary buffer and publishes it to the shared substreams cache, so
the published substream is not the on-disk LowCardinality(T) representation. A
sibling reader of the same streams, that is the parent subcolumn or
assumeNotNull() over it, adopts the cached column directly and ends up holding a
nullable dictionary under a declared type that is not nullable. Depending on the
build that surfaces as wrong values, Code: 49, or an abort on a bad cast.

Nothing mutated the published column; it was never the right representation.

Build the buffer from the pre-promotion type instead, which NullableSubcolumnCreator
still knows and now passes to the wrapper, and let the existing promotion in
applyParentNullMapToExtractedSubcolumn promote the private per-range column
afterwards. That keeps a single promotion owner and leaves the published
substreams in the representation a reader of the parent expects. The new
constructor parameter enters getHash() so the two flavours of the wrapper cannot
share a pooled instance.

Promoting on a private copy at the in-place promotion instead was evaluated and
measured to be a no-op: while the buffer is pre-promoted, that code is
unreachable, because its guard is !nestedIsNullable().

Wide parts were unaffected, since MergeTreeReaderWide reads each column
separately, and so was the getSubcolumn branch taken when
write_marks_for_substreams_in_compact_parts is disabled, which already copies.

Regression from ClickHouse#108679, which introduced this read path. Affects master and 26.7.

Related: ClickHouse#100394
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…6-carrier3-nonnullable-lc

Fix server abort for non-nullable LowCardinality tuple-element sort key
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 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.

4 participants