Skip to content

Do not execute functions that throw on the default value over the whole LowCardinality dictionary - #117359

Merged
alexey-milovidov merged 7 commits into
masterfrom
fix-low-cardinality-default-arguments-throwing-functions-117205
Sep 20, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
fix-low-cardinality-default-arguments-throwing-functions-117205

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

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 to CHANGELOG.md):

Fixed IPv4StringToNum, IPv6StringToNum, isIPAddressInRange, parseDateTime, parseDateTime64, parseDateTimeInJodaSyntax, parseTimeDelta, parseReadableSize, toModifiedJulianDay, JSONMergePatch, stringToH3 and the H3 index functions throwing an exception on entirely valid LowCardinality data, because they were executed over the dictionary, which always contains the type's default value.

Documentation entry for user-facing changes

A ColumnUnique dictionary always stores the type's default value at index 0, even when no row references it. A function that claims canBeExecutedOnDefaultArguments is executed on the whole dictionary rather than on the values rows actually reference, so a function that throws on the default value threw on entirely valid data — at pure default settings, including on a plain MergeTree read:

CREATE TABLE t (ip LowCardinality(String)) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t SELECT concat('10.0.0.', toString(number % 250 + 1)) FROM numbers(1000);
SELECT count(), max(IPv4StringToNum(ip)) FROM t;
-- Code: 675. DB::Exception: Invalid IPv4 value: while executing function IPv4StringToNum
-- on arguments __table1.ip LowCardinality(String)
-- LowCardinality(size = 0, UInt8(size = 0), Unique(size = 1, String(size = 1)))

Note Unique(size = 1) over a size = 0 chunk: the only value being converted is the reserved default. A WHERE filter could not avoid the throw either, since filtering keeps the dictionary.

The escape hatch already existed — modulo, intDiv, throwIf, toStartOfInterval and the toXxx conversion family decline the contract for exactly this reason — which also made the behaviour inconsistent: toIPv4(ip) worked over a LowCardinality(String) column while its documented equivalent IPv4StringToNum(ip) always threw.

Declined for IPv4StringToNum, IPv6StringToNum, isIPAddressInRange, parseDateTime and parseDateTime64, parseDateTimeInJodaSyntax, parseTimeDelta, parseReadableSize, toModifiedJulianDay, JSONMergePatch, stringToH3, and every H3 function that validates a cell or edge index — 0 is not a valid H3 index. Where a variant cannot throw the fast path is kept: the OrNull/OrDefault/OrZero variants, and the throwing variants when cast_ipv4_ipv6_default_on_conversion_error or functions_h3_default_if_invalid is enabled.

s2CellsIntersect, s2CapContains and s2RectContains validate their cell arguments, throw on cell id 0 and return UInt8, so the dictionary path applies to them over a LowCardinality(UInt64) column as well. They decline the contract too.

Declining the contract only removes the unreferenced reserved dictionary entry, though. A mixed NULL / non-NULL LowCardinality(Nullable(...)) dictionary keeps a referenced NULL, and defaultImplementationForNulls executed the function over the nested dictionary rows before masking the nulls out, so the placeholder value behind the NULL still reached the parser and threw. The same failure occurred for a plain Nullable(String) column, so it is not specific to LowCardinality: createBlockWithNestedColumns leaves the rows behind a NULL untouched - for a column built as Nullable from the start that is the type's default value - and the whole nested column was executed unless the null ratio reached short_circuit_function_evaluation_for_nulls_threshold, which is 1 by default.

SELECT parseDateTime(x, '%Y-%m-%d')
FROM (SELECT arrayJoin([NULL, '2024-01-01']) :: Nullable(String) AS x);
-- Code: 41. DB::Exception: Unable to parse fragment %Y from  because readNumber4 requires size >= 4

So a function that declines canBeExecutedOnDefaultArguments is now not executed on those rows at all: they are filtered out first, exactly like the existing short-circuit path does, and their result is masked out as NULL anyway. The filtering only happens when the input actually contains a NULL, so a Nullable column without nulls keeps the straight path, and functions that accept the contract are unaffected.

isIPAddressInRange was reported before, in #39599, but that issue was closed as a duplicate of #34796, an unrelated performance issue, so the bug survived and the family was never audited.

Closes: #117205
Related: #39599


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

…le `LowCardinality` dictionary

A `ColumnUnique` dictionary always stores the type's default value at index 0,
even when no row references it. A function that claims
`canBeExecutedOnDefaultArguments` is executed on the whole dictionary rather
than on the values rows actually reference, so a function that throws on the
default value threw on entirely valid data - at pure default settings,
including on a plain `MergeTree` read:

    CREATE TABLE t (ip LowCardinality(String)) ENGINE = MergeTree ORDER BY tuple();
    INSERT INTO t SELECT concat('10.0.0.', toString(number % 250 + 1)) FROM numbers(1000);
    SELECT count(), max(IPv4StringToNum(ip)) FROM t;
    -- Code: 675. DB::Exception: Invalid IPv4 value: while executing function
    -- IPv4StringToNum on arguments __table1.ip LowCardinality(String)
    -- LowCardinality(size = 0, UInt8(size = 0), Unique(size = 1, String(size = 1)))

Note `Unique(size = 1)` over a `size = 0` chunk: the only value being
converted is the reserved default. A `WHERE` filter could not avoid the throw
either, since filtering keeps the dictionary.

The escape hatch already existed - `modulo`, `intDiv`, `throwIf`,
`toStartOfInterval` and the `toXxx` conversion family decline the contract for
exactly this reason - which also made the behaviour inconsistent:
`toIPv4(ip)` worked over a `LowCardinality(String)` column while its
documented equivalent `IPv4StringToNum(ip)` always threw.

Declined for `IPv4StringToNum`, `IPv6StringToNum`, `isIPAddressInRange`,
`parseDateTime` and `parseDateTime64`, `parseDateTimeInJodaSyntax`,
`parseTimeDelta`, `parseReadableSize`, `toModifiedJulianDay`,
`JSONMergePatch`, `stringToH3`, and every H3 function that validates a cell or
edge index - `0` is not a valid H3 index. Where a variant cannot throw the
fast path is kept: the `OrNull`/`OrDefault`/`OrZero` variants, and the
throwing variants when `cast_ipv4_ipv6_default_on_conversion_error` or
`functions_h3_default_if_invalid` is enabled.

`isIPAddressInRange` was reported before, in #39599, but that issue was closed
as a duplicate of #34796, an unrelated performance issue, so the bug survived
and the family was never audited.

Closes: #117205
Related: #39599
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a7ef4fa]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes the LowCardinality / Nullable default-argument path for a large set of throwing functions by teaching them to decline dictionary/default execution and by filtering NULL rows for nullable results. The scalar-returning cases look covered, but the fix is still incomplete: the !result_is_nullable branch in defaultImplementationForNulls still ignores canBeExecutedOnDefaultArguments, so several touched H3 validators with Array/Tuple results still throw on valid Nullable(UInt64) and LowCardinality(Nullable(UInt64)) input. Because the PR body now claims the contract is handled generically for Nullable rows, I would not merge it in the current state.

Findings

❌ Blockers

  • [src/Functions/IFunction.cpp:339-352] canBeExecutedOnDefaultArguments is still bypassed for functions whose result type cannot be Nullable. This branch always patches NULL rows to the nested default and executes the function on every row, so the new H3 overrides in files such as src/Functions/h3HexRing.cpp, src/Functions/h3Line.cpp, src/Functions/h3ToChildren.cpp, src/Functions/h3GetFaces.cpp, src/Functions/h3ToGeoBoundary.cpp, src/Functions/h3GetIndexesFromUnidirectionalEdge.cpp, and src/Functions/h3toGeo.cpp still reach validator.validateCell(0) / validateEdge(0) and throw INCORRECT_DATA on otherwise valid Nullable(UInt64) or LowCardinality(Nullable(UInt64)) data. That violates both the new IFunction contract comment and the PR description’s claim that declining functions are now filtered off NULL rows generically.
    Suggested fix: make the !result_is_nullable path honor canBeExecutedOnDefaultArguments too, by filtering out NULL rows and expanding the skipped positions with the default value of the non-nullable result type; alternatively, each affected function needs an explicit useDefaultImplementationForNulls() = false path that produces defaults without executing on null rows. Add a focused regression for one Array result (h3HexRing or h3GetFaces) and one Tuple result (h3ToGeo or h3GetIndexesFromUnidirectionalEdge) over both Nullable(UInt64) and LowCardinality(Nullable(UInt64)).
Tests
  • ⚠️ The new coverage exercises only the scalar-returning H3/S2 family on Nullable input. It does not pin the still-touched Array/Tuple H3 functions that go through the non-nullable result branch, so the contract the PR now documents remains untested exactly where the bug survives.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: fix the non-nullable-result Nullable path so canBeExecutedOnDefaultArguments is honored there too, and add one focused regression for an Array-returning H3 function and one for a Tuple-returning H3 function.

LLVM Coverage Report

Measured on commit a7ef4fa.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.70% +0.10%

Changed lines: Changed C/C++ lines covered: 134/190 (70.53%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
Comment thread src/Functions/parseDateTime.cpp Resolved
@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

The same defect is live in the s2 family, which this PR's census does not cover: s2CellsIntersect, s2CapContains and s2RectContains all validate their cell arguments and throw on cell id 0, all return UInt8 (so the return type is wrapped back into LowCardinality and the dictionary path is taken), and none of them overrides canBeExecutedOnDefaultArguments. Reachability is identical to the H3 functions the PR fixes: a LowCardinality(UInt64) column created under allow_suspicious_low_cardinality_types = 1.

Verified on current master (26.9.1.417), with the other arguments constant so the single LowCardinality argument goes through the dictionary:

SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE t (c LowCardinality(UInt64)) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t SELECT geoToS2(37.0 + number / 100, 55.0 + number / 100) FROM numbers(10);
SELECT max(s2CellsIntersect(c, geoToS2(37.0, 55.0))) FROM t;
-- Code: 36. DB::Exception: First cell (id 0) is not valid in function s2CellsIntersect ...
--   on arguments ... Unique(size = 1, UInt64(size = 1)) ...
SELECT max(s2CapContains(c, 1.0, geoToS2(37.0, 55.0))) FROM t;
-- Code: 36. DB::Exception: Center (id 0) is not valid ...
SELECT max(s2RectContains(geoToS2(36.0, 54.0), geoToS2(38.0, 56.0), c)) FROM t;
-- Code: 36. DB::Exception: Point is invalid ...

The non-LowCardinality control (CAST(c AS UInt64)) returns correct results in all three spellings. Since the PR does not touch the s2 sources, these keep throwing after it merges.

A boundary observation that may save you the rest of the census: the dictionary path is only taken when the return type itself can live inside LowCardinality, so throwing functions whose result is a Tuple, Array or DateTime64 are not affected even without the override — that is why for example ULIDStringToDateTime (throws on any string whose length is not 26, but returns DateTime64), readWKTPoint and s2ToGeo/s2GetNeighbors cannot be triggered this way. The remaining exposure is exactly: throws on the type default, returns an LC-compatible scalar, and no canBeExecutedOnDefaultArguments override.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit a7ef4fa1a041defa4854ab14fa325208201070e1 with master failed: RuntimeError: CI logs cluster query failed: SELECT file, countIf(side = 'pr') AS pr_cou….

See the job log for details.

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 4, 2026
alexey-milovidov and others added 2 commits September 10, 2026 05:59
…-default-arguments-throwing-functions-117205
…default arguments

Address review: `canBeExecutedOnDefaultArguments` returning `false` removed only the
*unreferenced* reserved dictionary entry. A mixed `NULL` / non-`NULL`
`LowCardinality(Nullable(...))` dictionary keeps a *referenced* `NULL`, and
`defaultImplementationForNulls` executed the function over the nested dictionary rows
before masking the nulls out, so the placeholder value behind the `NULL` still reached
the parser and threw:

    SELECT parseDateTime(x, '%Y-%m-%d')
    FROM (SELECT arrayJoin([NULL, '2024-01-01']) :: LowCardinality(Nullable(String)) AS x);
    -- Code: 41. DB::Exception: Unable to parse fragment %Y from  because readNumber4
    -- requires size >= 4

The same failure occurred for a plain `Nullable(String)` column, so this is not specific
to `LowCardinality`: `createBlockWithNestedColumns` leaves the rows behind a `NULL`
untouched - for a column built as `Nullable` from the start that is the type's default
value - and the whole nested column was executed unless the null ratio reached
`short_circuit_function_evaluation_for_nulls_threshold`, which is `1` by default.

A function that declines `canBeExecutedOnDefaultArguments` is now not executed on those
rows at all: they are filtered out first, exactly like the existing short-circuit path
does, and their result is masked out as `NULL` anyway. The filtering only happens when
the input actually contains a `NULL`, so a `Nullable` column without nulls keeps the
straight path. Functions that accept the contract are unaffected.

`s2CellsIntersect`, `s2CapContains` and `s2RectContains` were missing from the census:
they validate their cell arguments, throw on cell id `0` and return `UInt8`, so the
dictionary path applies to them over a `LowCardinality(UInt64)` column. They decline the
contract now as well.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @zlareb1, thank you - confirmed and fixed in 88f860e. s2CellsIntersect, s2CapContains and s2RectContains now decline canBeExecutedOnDefaultArguments, and the test covers all three spellings from your repro over a LowCardinality argument.

Your boundary observation matches what the census used: the dictionary path is only taken when the result type itself can live inside LowCardinality, so the Tuple/Array/DateTime64-returning members of the family (s2ToGeo, s2GetNeighbors, s2CapUnion, s2Rect*, ULIDStringToDateTime, readWKTPoint) are not reachable this way and were left alone.

While at it, the same commit closes a second, wider hole that clickhouse-gh pointed out on parseDateTime.cpp: declining the contract only drops the unreferenced reserved dictionary entry, so a mixed NULL / non-NULL dictionary - and, as it turns out, a plain Nullable column with no LowCardinality at all - still executed the function on the rows behind a NULL. Those rows are now filtered out before execution.

@Ergus Ergus self-assigned this Sep 14, 2026
Ergus
Ergus previously requested changes Sep 14, 2026

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

Needs to reach also h3ToString (same class, same reachability)

"a Nullable column without nulls keeps the straight path": is true of the filtering but not of the fast path.

short_circuit_function_evaluation_for_nulls = 0 is non-honoured for declining functions. Is that intended? Cause it is a semantic change to a user-facing setting??

Comment thread src/Functions/IFunction.cpp Outdated
}

if (all_columns_constant || all_numeric_types)
if (all_columns_constant || (all_numeric_types && !must_not_execute_on_null_rows))

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.

IIUC this drops the numeric fast path unconditionally for every declining function. (Including when the column has no nulls at all)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 You are right, and it is fixed in ae57944.

The flag alone drove the decision, so every declining function lost the numeric fast path even when the Nullable argument did not contain a single NULL. The filtering is only required when a NULL is actually present, so it is now keyed on that: anyArgumentHasNullRows does a memoryIsZero scan over the arguments' null maps, and only for a function that declines the contract. Without a NULL in the input, such a function now takes exactly the same path as before this pull request, fast path included.

New test 05230_declining_default_arguments_nullable_no_nulls_fast_path pins it via ProfileEvents['DefaultImplementationForNullsRows'], which is only accounted on the non-fast path: 0 for a Nullable(UInt64) argument without a NULL, non-zero once one NULL is present.

Comment thread src/Functions/IFunction.cpp Resolved
alexey-milovidov and others added 3 commits September 19, 2026 11:27
…-default-arguments-throwing-functions-117205
…, and cover `h3ToString`

Three items from @Ergus:

- The numeric fast path of `defaultImplementationForNulls` was given up for *every* function
  that declines `canBeExecutedOnDefaultArguments`, even when the `Nullable` argument does not
  contain a single NULL. The filtering is only required when a NULL is actually present, so it
  is now keyed on `anyArgumentHasNullRows` - a `memoryIsZero` scan of the arguments' null maps,
  done only for a declining function - instead of on the flag alone. Without a NULL, such a
  function takes exactly the same path as before this pull request.

- `h3ToString` was missing from the census: it validates its cell argument, throws on the
  invalid index `0` and returns `String`, so the `LowCardinality` dictionary path applies to it.
  It declines the contract now as well.

- `short_circuit_function_evaluation_for_nulls` is deliberately not honoured for a declining
  function: for it the filtering is not an optimization but a correctness requirement, because
  the value stored behind a NULL is the default value of the argument type and executing on it
  throws on otherwise valid data. The rows are masked out as NULL either way, so no result
  changes - only the exception disappears. This is now stated in the setting's description.

New test `05230_declining_default_arguments_nullable_no_nulls_fast_path` asserts via
`ProfileEvents['DefaultImplementationForNullsRows']` that a `Nullable` argument without a NULL
keeps the fast path, while an argument containing a NULL takes the filtering path.
`05089_low_cardinality_default_arguments_throwing_functions` covers `h3ToString` over a
`LowCardinality` argument and over a mixed NULL / non-NULL dictionary.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…by the value behind it

Both failures are the intended consequence of the fix and were not adapted:

- `03784_functions_various_bugs` asserted `ILLEGAL_DIVISION` for
  `intDiv(1, materialize(CAST(null AS LowCardinality(Nullable(Int8)))))`. That exception was the
  bug: `intDiv` declines `canBeExecutedOnDefaultArguments` and was still executed on the
  dictionary default `0` stored behind the NULL. The result is `NULL` now, which is what dividing
  by a NULL must produce; the test records the correct answer instead.

- `04401_key_condition_is_not_distinct_from` still gets its `ILLEGAL_DIVISION` from the non-NULL
  granule of `intDiv(k, 0)`, but the NULL granule no longer raises, so it can emit its row before
  the other granule fails. `FORMAT Null` keeps the exception assertion free of that partial
  output, which is not deterministic between granules.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117359&sha=88f860e0586a370c177ea5c49321eb5538454aff&name_0=PR&name_1=Fast%20test
#117359

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @Ergus, thank you - all three points are addressed in ae57944, on top of a fresh master merge.

h3ToString - correct, it belongs to the census: it validates its argument, throws Invalid H3 index on the index 0 and returns String, so the dictionary path applies. It declines canBeExecutedOnDefaultArguments now, and 05089_low_cardinality_default_arguments_throwing_functions covers it both over a plain LowCardinality(UInt64) argument and over a mixed NULL / non-NULL dictionary.

The fast path - you are right, my claim held for the filtering but not for the fast path: the numeric fast path was given up for every declining function, including when the Nullable argument contained no NULL at all. The decision is keyed on the actual presence of a NULL now (anyArgumentHasNullRows, a memoryIsZero scan over the null maps, done only for a declining function), so without a NULL nothing changes relative to master. Pinned by the new test 05230_declining_default_arguments_nullable_no_nulls_fast_path through ProfileEvents['DefaultImplementationForNullsRows'].

short_circuit_function_evaluation_for_nulls = 0 - intended, and now documented in the setting's description. The setting controls an optimization that cannot change a value: the rows containing a NULL are masked out as NULL either way. For a declining function the only thing it would change is whether the query throws, and that exception is the bug - the value behind a NULL is the default value of the argument type, not user data. Honouring the setting there would make the correctness of a valid query depend on a performance setting.

Details in the two thread replies.

Additionally, the two Fast test failures were the intended consequence of the fix and are adapted in 1769574: intDiv(1, NULL) returns NULL instead of ILLEGAL_DIVISION (03784_functions_various_bugs pinned the old exception), and in 04401_key_condition_is_not_distinct_from the NULL granule of intDiv(k, 0) no longer raises, so it can emit its row before the non-NULL granule raises - the exception assertion uses FORMAT Null now to stay deterministic.

Comment thread src/Functions/IFunction.h
*
* *Not* useful when executing on Nullable columns. The value behind a NULL is
* not necessarily default. E.g.:
* Also used when executing on Nullable columns: `createBlockWithNestedColumns` leaves the rows

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.

canBeExecutedOnDefaultArguments() still has no effect for the Nullable path when the result type itself cannot be Nullable. defaultImplementationForNulls() returns through the !result_is_nullable branch in src/Functions/IFunction.cpp:339-352, patches NULL rows to the nested default, and then executes the function on that value.

That means the array/tuple-returning H3 functions touched here are still broken on valid Nullable input even after this override. For example:

SELECT h3HexRing(x, 1)
FROM (SELECT arrayJoin([NULL, 599686042433355775])::Nullable(UInt64) AS x);

still reaches validator.validateCell(0) and throws. The same gap applies to the other touched H3 validators with Array/Tuple results (h3Line, h3ToChildren, h3ToGeo, h3GetIndexesFromUnidirectionalEdge, ...). If the intent is to make the canBeExecutedOnDefaultArguments contract cover Nullable rows too, these need explicit useDefaultImplementationForNulls() = false handling rather than just this override.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov
alexey-milovidov dismissed Ergus’s stale review September 20, 2026 20:04

Answered. No semantic change, only disabling the incorrect optimization.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 20, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 20, 2026
Merged via the queue into master with commit 9b323a0 Sep 20, 2026
175 of 177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-low-cardinality-default-arguments-throwing-functions-117205 branch September 20, 2026 20:35
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 12, 2026
…thmetic

The default NULL implementation executes a function over the nested column,
rows behind a NULL included, unless the function declines
canBeExecutedOnDefaultArguments. Behind a NULL of a Nullable(String) the value
is the empty string. The interval functions accept the contract but parse a
String date per row, so they threw CANNOT_PARSE_DATETIME on valid data. Since
ClickHouse#117359 formatDateTime declines, so its NULL rows hold '' instead of a
formatted default date, which made addDate(formatDateTime(x, ...), INTERVAL ...)
regress in 26.10 (ClickHouse#130381).

Three entry points reach the parser, each with its own NULL handling:
add*/subtract* (FunctionDateOrDateTimeAddInterval), plus/minus with
String +/- Interval (plus strips Nullable and runs the prepared add* on the
nested columns) and addDate/subDate (FunctionOpDate strips Nullable and calls
plus/minus).

The hook takes no arguments, while only a String date throws: declining it
unconditionally would take the Nullable numeric fast path and the
LowCardinality dictionary path away from Date and DateTime arguments. Add an
overload that receives the arguments and defaults to the existing hook (the
shape of getReturnTypeForDefaultImplementationForDynamic), call it from the
two readers, and override it in the three entry points to decline only for a
String date.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
qoega pushed a commit to qoega/ClickHouse that referenced this pull request Nov 19, 2026
…lable arguments

A function that accepts canBeExecutedOnDefaultArguments() is executed over
the whole LowCardinality dictionary, which always stores the type's default
value at index 0 even when no row references it, and over the nested values
behind NULLs, which hold the type's default for columns read from a table.
A function that throws on that default value therefore rejects valid data:

    SELECT prettyPrintJSON(materialize(toLowCardinality('{"a":1}')));
    -- Code: 36. Invalid JSON string ...: The document is empty
    SELECT printf(x, 1) FROM (SELECT arrayJoin(['%d', NULL]) AS x);
    -- Code: 42. Number of arguments for function printf doesn't match

ClickHouse#117359 made such functions decline the contract; these were missed:
prettyPrintJSON, printf, formatQuery, formatQuerySingleLine,
parseQueryToJSON, formatQueryFromJSON (ClickHouse#122277, ClickHouse#121498), and, found by
sweeping all regular functions, conv, toBool, MGRSToGeo, readWKTPoint,
readWKBPoint, filesystemAvailable/Capacity/Unreserved, the throwing
base32/base58/base64/base64URL decoders, encrypt/decrypt and the MySQL and
try variants, divideDecimal, clamp, widthBucket, regexpPosition, the tuple
division functions, hop/hopStart/hopEnd, s2ToGeo, s2CapUnion, s2RectAdd,
s2RectUnion and s2RectIntersection.

Each now declines the contract, so the framework evaluates only the values
the rows hold (the minimal dictionary, NULL rows filtered first). Where one
class serves both a throwing and a non-throwing name (formatQuery...OrNull,
try*Decode and the encoders, multiplyDecimal, tuple plus/minus/multiply/
intDivOrZero, tumble*), only the throwing ones decline, keeping the fast
path for the rest. An empty IV is valid as "no IV" in the non-AEAD AES
modes, so the AES comment names only the key.

The test runs every function over a LowCardinality column and over a
Nullable column holding a NULL, and keeps rows that really hold an invalid
value as negative controls. It clamps
short_circuit_function_evaluation_for_nulls_threshold to at least 1: at a
threshold of 0.5 or less the 50% NULL inputs are short-circuited and the
Nullable cases would pass without the fix.

Closes ClickHouse#122277
Closes ClickHouse#121498

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

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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

4 participants