Skip to content

Fix LOGICAL_ERROR in accurateCastOrNull to a Nullable(Tuple) with a LowCardinality element - #132577

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/accurate-cast-or-null-tuple-low-cardinality-element
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/accurate-cast-or-null-tuple-low-cardinality-element

Conversation

@groeneai

@groeneai groeneai commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #132543

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 accurateCastOrNull and accurateCastOrDefault to a Nullable(Tuple) with a LowCardinality element, which threw LOGICAL_ERROR (ColumnUnique can't contain null values) when an element value did not fit, was NULL, or came from a LowCardinality(Nullable) column. The result is now the same as for the plain element type: NULL when an element cannot be converted, the converted tuple otherwise.

Description

On 26.10.3.7, accurateCastOrNull(tuple(toLowCardinality(materialize(toNullable('ab')))), 'Nullable(Tuple(LowCardinality(String)))') throws LOGICAL_ERROR instead of returning ('ab'), and so does any element value that does not fit ('abc' to LowCardinality(FixedString(2))) or is NULL; debug builds abort. Found by the automated review of #132543 (thread); it predates #119183.

Under accurateCastOrNull a Nullable(Tuple) asks each element conversion to report a failure as NULL. A plain element does it by returning Nullable(T), which the tuple strips while folding its null map into the tuple's NULLs. Nullable(LowCardinality(T)) is not a type, so a LowCardinality(T) element inserted the NULL into its non-nullable dictionary. A LowCardinality(Nullable(String)) source always carries the NULL key, so even a non-NULL value threw.

Now the tuple converts such an element as LowCardinality(Nullable(T)), reads its NULLs as failures and restores the declared dictionary with cloneWithDefaultOnNull. An element conversion now also gets the null map of the surrounding Nullable(Tuple), merged with a Nullable element's own, so placeholders under its NULL rows are not converted; this also fixes CAST of such a row to Nullable(Tuple(Nullable(String))) from an Enum element and to Nullable(Tuple(String)) from a Nullable(Enum) one, which throw UNKNOWN_ELEMENT_OF_ENUM on 26.10.3.7. T and LowCardinality(T) sources keep their previous path; a successful conversion that changes the type (String to LowCardinality(FixedString(2))) costs ~23% more in a debug build. Tuple(LowCardinality(T)) without the outer Nullable is still refused (Code 43): the same check decides whether IN sets and the primary key analysis convert a key with accurateCastOrNull.

The new test aborts a master debug build at its first query and passes with the fix; its LowCardinality lines print what the plain element type prints. Existing accurateCast*, LowCardinality cast and Nullable(Tuple) tests pass unchanged.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/132577]

groeneai and others added 3 commits November 18, 2026 03:19
…owCardinality element

Under accurateCastOrNull, a Nullable(Tuple) asks each element conversion to
report a failed conversion as NULL, and extractTupleElementConversionFailures
turns those NULLs into a NULL tuple. A non-nullable element reports them by
returning Nullable(T), which the extractor strips. Nullable(LowCardinality(T))
is not a type, so for a LowCardinality(T) element prepareUnpackDictionaries
converted to T with report_failures_as_null and inserted the resulting
ColumnNullable into the declared non-nullable dictionary: ColumnUnique threw
"ColumnUnique can't contain null values" (Code 49, an abort in debug builds).
A LowCardinality(Nullable(String)) source always carries the NULL key, so even
a non-NULL value threw; a Nullable(Nothing) source gave Code 44 instead.

The tuple now converts a LowCardinality(T) element whose source type differs
as LowCardinality(Nullable(T)), the type that carries NULL for a LowCardinality
target (as cast_keep_nullable does). The extractor folds its NULLs into the
failures and restores the declared dictionary with cloneWithDefaultOnNull, the
analogue of stripping Nullable from a plain element. The conversion itself goes
through the existing LowCardinality(Nullable(T)) path, including its Variant,
Dynamic and onlyNull branches. An identical source type cannot fail nor carry a
NULL, so it keeps its dictionary-encoded path.

Every LowCardinality line of the new test prints the same as the same input
with the plain element type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A tuple element of declared type LowCardinality(T) is converted as
LowCardinality(Nullable(T)) only when its source can fail. A source of type T
or LowCardinality(T) converts by identity and never reports a failure, so it
now keeps its previous conversion. This removes the measured ~26% (debug build)
dictionary copy from String -> LowCardinality(String), the common shape; a
type-changing conversion such as String -> LowCardinality(FixedString(2))
still pays it (~23%, debug build, 10M rows).

The test gains a line with T and LowCardinality(T) sources next to an element
whose conversion fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the two-line conversion_types comment in createTupleWrapper to one line.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 rounds, 3 distinct findings) plus my own review (5 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ A T source (String to LowCardinality(String)) took the slower LowCardinality(Nullable(T)) path although it cannot fail AGREE, fixed @ 45bb880 the check compares the dictionary types, so T and LowCardinality(T) sources keep the previous path (+26% to within noise, debug)
2 ⚠️ The accurateCastOrDefault line cannot tell a substituted default from a leaked NULL (raised twice) DISAGREE for this target the default is always NULL: an explicit default is refused (Code 36, also on 26.10.3.7, because the default LowCardinality implementation strips LowCardinality from the default's type) and a non-Nullable target is refused (Code 43), so both cases give the same NULL. The line aborts on master, and the changelog claims only NULL
3 ❌ Tuple(LowCardinality(T)) without the outer Nullable is still refused DISAGREE the argument check's deliberate Code 43 (CastOverloadResolver.cpp:121), the same on 26.10; that check also decides whether IN sets and primary key analysis use accurateCastOrNull for a key, so lifting it is a separate change
4 💡 No line covers an unchanged identity element next to a failing one AGREE, fixed @ 45bb880 one multi-row line
5 💡 That line does not prove the identity path is taken DISAGREE the path only saves cost and gives the same output; proving it would pin dictionary slot counts
6 💡 The dumpColumnStructure line pins the dictionary size 3 AGREE, not changed deterministic; the extra slot is cloneWithDefaultOnNull's existing behaviour
7 💡 An Enum source to a LowCardinality(String) element no longer uses the dedicated wrapper AGREE, not changed cost only; the conversion cannot fail

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

Session id: cron:clickhouse-review-slot-9:20261118-040502

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. accurateCastOrNull(tuple(materialize('abc')), 'Nullable(Tuple(LowCardinality(FixedString(2))))') aborts a master debug build (rc=134, ColumnUnique can't contain null values) every time; 26.10.3.7 returns Code 49.
b Root cause explained? The tuple asks each element conversion to report a failure as NULL. A LowCardinality(T) element has no Nullable form, so the conversion inserted the NULL into the non-nullable dictionary of T.
c Fix matches root cause? Yes. The element is converted as LowCardinality(Nullable(T)), its NULLs become failures and the declared dictionary is restored with cloneWithDefaultOnNull. No guard, no new code in the conversions.
d Test intent preserved / new tests added? New test 05829_accurate_cast_or_null_nullable_tuple_low_cardinality_element, non-nullable and nullable dictionary targets.
e Both directions demonstrated? Master: abort at query 1. Fix: matches the reference; 50/50 randomized runs. Disabling either half of the fix reddens the test.
f Fix is general across code paths? One substitution covers every source path: plain, Nullable, Nullable(Nothing), LowCardinality (both insert paths), Variant, Dynamic, nested Tuple.
g Fix generalizes across inputs (params/datatypes/wrappers)? String, FixedString, UInt8 targets; NULL, fitting, non-fitting, empty, constant, multi-row inputs; accurateCastOrDefault; each LowCardinality result equals the plain-type result.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only the LOGICAL_ERROR cases change. 89 existing cast tests pass.
i Invariants and contracts preserved? Every element again has its declared column type (columnMatchesType); LowCardinality(Nullable(T)) elements and tuples in Array/Map are untouched.

Session id: cron:clickhouse-impl-slot-7:20261118-023700

@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a9d0161]

Summary: ❌

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

AI Review

Summary

The PR fixes failure reporting for accurateCastOrNull and accurateCastOrDefault with LowCardinality tuple elements and preserves parent null maps during element conversion. Both earlier reported repros are fixed, and all 32 rows of the new regression test match its reference on the current head's ARM fast-test binary. One pre-existing parent-null validation defect remains in the touched conversion path.

The temporary LowCardinality(Nullable(T)) element is normalized by extractTupleElementConversionFailures before tuple assembly. Outer nullable wrapping, ExecutableFunctionCast, accurateCastOrDefault, internal castColumn callers, and Set/KeyCondition consequently receive the declared tuple layout.

Findings

❌ Blockers

  • src/Functions/FunctionsConversion.cpp:3302: Parent-null rows must be ignored before validating element nullability. The new mask merge runs after the non-nullability check, so ordinary CAST of Nullable(Tuple(Nullable(String))) to Nullable(Tuple(String)) rejects a null tuple's placeholder with CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN. The dictionary-backed case fails at containsNull in prepareUnpackDictionaries for the same reason. Reproduced on the current head, including a mixed nonconstant column; accurateCast returns the expected rows. Filter parent-null rows before element validation, or apply the parent mask to both checks, with regression coverage that preserves rejection of a non-null tuple containing a null element. This predates the PR; a linked tracking issue is also sufficient.
SELECT CAST(t, 'Nullable(Tuple(String))')
FROM values('t Nullable(Tuple(Nullable(String)))',
    (NULL), (tuple('a')));
-- Expected: NULL, ('a'); actual: exception Code 349.
Final Verdict

Status: ❌ Block. Fix the remaining parent-null validation case with a focused regression test, or link an issue tracking this pre-existing defect.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 18, 2026
Comment thread src/Functions/FunctionsConversion.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a69582f61 with master c3ec2bd66 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

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

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

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.78 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.0 s 15.0 s +9.5 s (+173%)
Compile time of recompiled translation units

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

Job report

…le result

A `LowCardinality(T)` tuple element now converts as `LowCardinality(Nullable(T))`,
so its conversion goes through the nullable-result branch of `prepareRemoveNullable`.
That branch passed no null map to the conversion when the source is not nullable,
so a NULL row of a `Nullable(Tuple(...))` source was converted from its placeholder
value. An `Enum` element under such a row (`arrayElementOrNull` past the end,
`join_use_nulls`, ...) then threw `UNKNOWN_ELEMENT_OF_ENUM` for the placeholder 0
in `accurateCastOrNull` / `accurateCastOrDefault` to `LowCardinality(String)` or
`LowCardinality(FixedString(N))`, which returned NULL before this PR.

When neither type is nullable, `prepareRemoveNullable` returns the conversion
itself, which gets the caller's null map. The nullable-result branch now passes
it through too when the source is not nullable. The same
change fixes `CAST` of such a row to `Nullable(Tuple(Nullable(String)))` and
`Nullable(Tuple(LowCardinality(Nullable(String))))` from an `Enum` element, and to
`Nullable(Tuple(Nullable(Enum8(...))))` from a `String` element, which threw on
master (26.10.3.7 too).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 18, 2026
Comment thread src/Functions/FunctionsConversion.cpp Resolved
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 18, 2026 08:19

AI review of a later commit does not approve the PR, see the AI Review comment.

…oveNullable

A NULL row of a `Nullable(Tuple(...))` holds placeholder values in its
elements. When the element is itself `Nullable`, its null map can be zero
under such a row (e.g. after `CAST(... AS Nullable(Tuple(Nullable(Enum8(...)))))`),
and both nullable-source branches of `prepareRemoveNullable` replaced the
parent's null map with the element's. The enum wrappers then formatted the
placeholder `0` and threw `UNKNOWN_ELEMENT_OF_ENUM`:

    SELECT accurateCastOrNull(
        CAST(arrayElementOrNull([tuple(materialize('a'::Enum8('a' = 1)))], 2)
            AS Nullable(Tuple(Nullable(Enum8('a' = 1))))),
        'Nullable(Tuple(LowCardinality(String)))');

This throws on 26.10.3.7, on master 361455a and on the previous head of this
PR; plain `CAST` to `Nullable(Tuple(String))` and
`Nullable(Tuple(Nullable(String)))` throws the same way. Both branches now pass
the union of the two null maps.

The `LowCardinality` wrapper converts only the dictionary when the nested
types match, so it no longer forwards the row-aligned parent map there:
merging it with the dictionary's null map would read past the dictionary
(a PODArray bounds assertion in a debug build, measured by reverting that hunk).

Reported by the automated review:
ClickHouse#132577 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
}

const ColumnNullable * nullable_source = typeid_cast<const ColumnNullable *>(arguments.front().column.get());
const ColumnPtr source_with_parent_nulls = addParentNulls(arguments.front().column, parent_nullable_source);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Blocker] Apply the parent mask before validating non-nullable elements

The new addParentNulls call runs after the memoryIsZero check above. If a nullable element's placeholder is itself NULL, ordinary CAST still rejects the row before reaching the merged parent mask, even though the entire source tuple is NULL and the target permits that.

Reproduced with the fast-test binary for a9d01616:

SELECT CAST(t, 'Nullable(Tuple(String))')
FROM values('t Nullable(Tuple(Nullable(String)))',
    (NULL), (tuple('a')));

This throws CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN instead of returning NULL and ('a'). The equivalent accurateCast succeeds. LowCardinality(Nullable(String)) to LowCardinality(String) also fails through the earlier containsNull check in prepareUnpackDictionaries.

Exclude parent-null rows before element validation, or make both checks reject only element nulls in parent-non-null rows. Add a focused regression that still rejects a non-null tuple containing a null element. This predates the PR; linking a tracking issue is sufficient if it is handled separately.

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.

This predates the PR: master before it (361455a) and 26.10.3.7 throw the same Code 349 for both queries, and the PR does not change the not-NULL precheck or the containsNull check. I am fixing it in a separate PR, which also covers the element parsing conversions that fail under NULL tuple rows, and will link it here.

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.

The separate PR is #132672: it converts only the non-NULL rows of a Nullable(Tuple) source, and its test keeps a NULL element under a non-NULL row throwing 349.

@PedroTadim

Copy link
Copy Markdown
Member

@nihalzp also need help here

clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Nov 24, 2026
A NULL row of a Nullable(Tuple) stores placeholders in its elements ('' for
a String, a NULL in a Nullable element, 0 for an Enum). prepareRemoveNullable
ran the Tuple conversion over the nested column of every row, and the
element conversions do not all read the null map they are handed: the
function adaptors parse the placeholder '' (Code 32/38), the not-NULL
precheck of a Nullable element and the LowCardinality containsNull() check
see the element NULL under a NULL tuple row (Code 349), and an Enum
placeholder 0 serialized to String throws 691. So CAST, INSERT SELECT and
ALTER TABLE ... MODIFY COLUMN from a Nullable(Tuple) with NULL rows threw
instead of returning NULL for those rows; the ALTER left a stuck mutation
and an unreadable column.

accurateCast already filters the NULL rows out, converts, and expands the
result (exclude_source_nulls, ClickHouse#120674). Enable it for every cast type when
the source is a Nullable(Tuple) whose nested type changes. The filter costs
+1.2 ns/row per Int element and +4-5 ns/row per String element on blocks
that contain a NULL row (release 26.10.5.57, measured through accurateCast);
blocks without NULLs are unchanged. The nested values of NULL rows in the
result are now the column default, as with accurateCast.

Related: ClickHouse#132577

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants