Repository navigation
Do not execute functions that throw on the default value over the whole LowCardinality dictionary - #117359
Conversation
…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
|
Workflow [PR], commit [a7ef4fa] Summary: ❌
AI ReviewSummaryThis PR fixes the Findings❌ Blockers
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit a7ef4fa.
Changed lines: Changed C/C++ lines covered: 134/190 (70.53%) · Uncovered code |
|
The same defect is live in the Verified on current master (26.9.1.417), with the other arguments constant so the single 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- 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 |
Build profile diff (arm_release)Comparing commit See the job log for details. |
…-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]>
|
🕵 @zlareb1, thank you - confirmed and fixed in 88f860e. Your boundary observation matches what the census used: the dictionary path is only taken when the result type itself can live inside While at it, the same commit closes a second, wider hole that |
Ergus
left a comment
There was a problem hiding this comment.
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??
| } | ||
|
|
||
| if (all_columns_constant || all_numeric_types) | ||
| if (all_columns_constant || (all_numeric_types && !must_not_execute_on_null_rows)) |
There was a problem hiding this comment.
IIUC this drops the numeric fast path unconditionally for every declining function. (Including when the column has no nulls at all)
There was a problem hiding this comment.
🕵 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.
…-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]>
|
🕵 @Ergus, thank you - all three points are addressed in ae57944, on top of a fresh
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
Details in the two thread replies. Additionally, the two |
| * | ||
| * *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 |
There was a problem hiding this comment.
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.
…wing-functions-117205
Answered. No semantic change, only disabling the incorrect optimization.
…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]>
…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]>
Changelog category (leave one):
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,stringToH3and the H3 index functions throwing an exception on entirely validLowCardinalitydata, because they were executed over the dictionary, which always contains the type's default value.Documentation entry for user-facing changes
A
ColumnUniquedictionary always stores the type's default value at index 0, even when no row references it. A function that claimscanBeExecutedOnDefaultArgumentsis 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 plainMergeTreeread:Note
Unique(size = 1)over asize = 0chunk: the only value being converted is the reserved default. AWHEREfilter could not avoid the throw either, since filtering keeps the dictionary.The escape hatch already existed —
modulo,intDiv,throwIf,toStartOfIntervaland thetoXxxconversion family decline the contract for exactly this reason — which also made the behaviour inconsistent:toIPv4(ip)worked over aLowCardinality(String)column while its documented equivalentIPv4StringToNum(ip)always threw.Declined for
IPv4StringToNum,IPv6StringToNum,isIPAddressInRange,parseDateTimeandparseDateTime64,parseDateTimeInJodaSyntax,parseTimeDelta,parseReadableSize,toModifiedJulianDay,JSONMergePatch,stringToH3, and every H3 function that validates a cell or edge index —0is not a valid H3 index. Where a variant cannot throw the fast path is kept: theOrNull/OrDefault/OrZerovariants, and the throwing variants whencast_ipv4_ipv6_default_on_conversion_errororfunctions_h3_default_if_invalidis enabled.s2CellsIntersect,s2CapContainsands2RectContainsvalidate their cell arguments, throw on cell id0and returnUInt8, so the dictionary path applies to them over aLowCardinality(UInt64)column as well. They decline the contract too.Declining the contract only removes the unreferenced reserved dictionary entry, though. A mixed
NULL/ non-NULLLowCardinality(Nullable(...))dictionary keeps a referencedNULL, anddefaultImplementationForNullsexecuted the function over the nested dictionary rows before masking the nulls out, so the placeholder value behind theNULLstill reached the parser and threw. The same failure occurred for a plainNullable(String)column, so it is not specific toLowCardinality:createBlockWithNestedColumnsleaves the rows behind aNULLuntouched - for a column built asNullablefrom the start that is the type's default value - and the whole nested column was executed unless the null ratio reachedshort_circuit_function_evaluation_for_nulls_threshold, which is1by default.So a function that declines
canBeExecutedOnDefaultArgumentsis 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 asNULLanyway. The filtering only happens when the input actually contains aNULL, so aNullablecolumn without nulls keeps the straight path, and functions that accept the contract are unaffected.isIPAddressInRangewas 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]