Repository navigation
Fix logical error in functions with LowCardinality arguments over distributed tables - #108871
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260629-210700 |
|
cc @rschu1ze @KochetovNicolai — could you review this? The default |
|
Workflow [PR], commit [d19ce65] Summary: ✅
AI ReviewSummaryThis PR fixes the Final Verdict✅ No findings. |
|
Pushed an additional commit (
The other half can also break at runtime. The fast path strips one reached through planner header evaluation ( The Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260629-223700 |
|
Pre-PR validation gate refreshed for 68816ae (fallback row-count fix on top of the LowCardinality default-impl generalization). Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260630-001100 |
CI finish ledger — c54c83aFinish Workflow and Mergeable Check are green. Every failure below has an owner.
Earlier-SHA failures ( Session id: cron:our-pr-ci-monitor:20260630-053000 |
| -- Tags: shard | ||
|
|
||
| -- A constant LowCardinality argument is not counted as a full LowCardinality | ||
| -- argument when the result type is computed, so the result of concat() is wrapped | ||
| -- in LowCardinality. Over a distributed query the constness of an aggregation key | ||
| -- is dropped in the merging-aggregator header, so two non-constant LowCardinality | ||
| -- columns reach the default LowCardinality function implementation. This used to | ||
| -- throw LOGICAL_ERROR "Default functions implementation for LowCardinality is | ||
| -- supported only with a single LowCardinality argument". | ||
|
|
||
| DROP TABLE IF EXISTS t_04489; | ||
| CREATE TABLE t_04489 (d Dynamic) ENGINE = Memory; | ||
| INSERT INTO t_04489 VALUES (1), (2), ('a'), ('b'), (NULL); | ||
|
|
||
| SELECT concatAssumeInjective((SELECT toLowCardinality('p')), dynamicType(d)) AS type, count() | ||
| FROM remote('127.0.0.{1,2}', currentDatabase(), t_04489) | ||
| GROUP BY GROUPING SETS ((type)) ORDER BY type; | ||
|
|
||
| SELECT concat((SELECT toLowCardinality('p')), dynamicType(d)) AS type, count() | ||
| FROM remote('127.0.0.{1,2}', currentDatabase(), t_04489) | ||
| GROUP BY GROUPING SETS ((type)) ORDER BY type; | ||
|
|
||
| SELECT concatAssumeInjective((SELECT toLowCardinality(toNullable('p'))), dynamicType(d)) AS type | ||
| FROM remote('127.0.0.{1,2}', currentDatabase(), t_04489) | ||
| GROUP BY GROUPING SETS ((type)) ORDER BY type; | ||
|
|
||
| DROP TABLE t_04489; |
There was a problem hiding this comment.
Simplify the test and explain it, why we need concatAssumeInjective(), why remote()
| -- Tags: shard | |
| -- A constant LowCardinality argument is not counted as a full LowCardinality | |
| -- argument when the result type is computed, so the result of concat() is wrapped | |
| -- in LowCardinality. Over a distributed query the constness of an aggregation key | |
| -- is dropped in the merging-aggregator header, so two non-constant LowCardinality | |
| -- columns reach the default LowCardinality function implementation. This used to | |
| -- throw LOGICAL_ERROR "Default functions implementation for LowCardinality is | |
| -- supported only with a single LowCardinality argument". | |
| DROP TABLE IF EXISTS t_04489; | |
| CREATE TABLE t_04489 (d Dynamic) ENGINE = Memory; | |
| INSERT INTO t_04489 VALUES (1), (2), ('a'), ('b'), (NULL); | |
| SELECT concatAssumeInjective((SELECT toLowCardinality('p')), dynamicType(d)) AS type, count() | |
| FROM remote('127.0.0.{1,2}', currentDatabase(), t_04489) | |
| GROUP BY GROUPING SETS ((type)) ORDER BY type; | |
| SELECT concat((SELECT toLowCardinality('p')), dynamicType(d)) AS type, count() | |
| FROM remote('127.0.0.{1,2}', currentDatabase(), t_04489) | |
| GROUP BY GROUPING SETS ((type)) ORDER BY type; | |
| SELECT concatAssumeInjective((SELECT toLowCardinality(toNullable('p'))), dynamicType(d)) AS type | |
| FROM remote('127.0.0.{1,2}', currentDatabase(), t_04489) | |
| GROUP BY GROUPING SETS ((type)) ORDER BY type; | |
| DROP TABLE t_04489; | |
| -- Tags: shard | |
| -- The result type of a function over LowCardinality arguments is LowCardinality only when | |
| -- at most one argument is a non-constant LowCardinality column; constant arguments are not | |
| -- counted. Constness, however, is not preserved when blocks travel between servers, so at | |
| -- execution a function can receive more non-constant LowCardinality columns than its result | |
| -- type was derived for. This used to throw the LOGICAL_ERROR exception "Default functions | |
| -- implementation for LowCardinality is supported only with a single LowCardinality argument" | |
| -- (during query planning, before reading any data). Now the extra LowCardinality columns are | |
| -- materialized and the result matches local execution. | |
| -- | |
| -- Every element of the query is essential to break that invariant: | |
| -- * concatAssumeInjective: for an injective f, GROUP BY f(x, y) is rewritten into | |
| -- GROUP BY x, y and f is re-executed on top of the aggregation | |
| -- (goes away with optimize_injective_functions_in_group_by = 0). | |
| -- * (SELECT toLowCardinality('p')): a constant of a LowCardinality type. As a constant it is | |
| -- not counted for the result type, so the result type stays LowCardinality; but unlike an | |
| -- ordinary-typed constant it is not folded into a literal | |
| -- (goes away with enable_scalar_subquery_optimization = 0), and therefore it is not | |
| -- eliminated from the GROUP BY keys either - it stays a live aggregation key | |
| -- (compare: with (SELECT 'p') the constant key is removed and nothing fails). | |
| -- * Two shards: the initiator has to merge partially aggregated streams, and the merged key | |
| -- columns are always ordinary (non-constant) columns, so the scalar key loses its | |
| -- constness there (goes away with a single-address remote()). | |
| -- * Re-executing concatAssumeInjective over the merged keys then feeds two non-constant | |
| -- LowCardinality columns into a function whose declared result type is LowCardinality. | |
| CREATE TABLE t (s LowCardinality(String)) ENGINE = Memory; | |
| INSERT INTO t VALUES ('x'), ('y'), ('x'); | |
| SELECT concatAssumeInjective((SELECT toLowCardinality('p')), s) AS type, count() | |
| FROM remote('127.0.0.{1,2}', currentDatabase(), t) | |
| GROUP BY type | |
| ORDER BY type; |
| /// longer holds. | ||
| ColumnPtr indexes; | ||
| size_t new_input_rows_count = 0; | ||
| if (!canShareLowCardinalityDictionary(columns_without_low_cardinality)) |
There was a problem hiding this comment.
No need to introduce separate helper and iterate over args one more time, you can do smth like this
/// If the single-dictionary fast path applies (exactly one full LowCardinality argument and
/// every other argument constant), replace that column with its nested dictionary, resize
/// the constants to the dictionary size and return the dictionary indexes for the result.
/// Otherwise return nullptr and leave args unchanged: the declared LowCardinality result
/// type may rest on a constness that was lost at a pipeline boundary (e.g. a merged
/// aggregation key), and the caller falls back to full materialization.
ColumnPtr replaceLowCardinalityColumnByNestedAndGetDictionaryIndexes(
ColumnsWithTypeAndName & args, bool can_be_executed_on_default_arguments)
{
/// Scan first, mutate after: a second LowCardinality column may be discovered after the
/// first one, and args must stay intact for the caller's fallback.
const ColumnLowCardinality * low_cardinality_column = nullptr;
size_t low_cardinality_arg = 0;
for (size_t i = 0; i < args.size(); ++i)
{
if (const auto * lc = checkAndGetColumn<ColumnLowCardinality>(args[i].column.get()))
{
if (low_cardinality_column)
return nullptr;
low_cardinality_column = lc;
low_cardinality_arg = i;
}
else if (!isColumnConst(*args[i].column))
return nullptr;
}
if (!low_cardinality_column)
return nullptr;
auto & column = args[low_cardinality_arg];
const auto * low_cardinality_type = checkAndGetDataType<DataTypeLowCardinality>(column.type.get());
if (!low_cardinality_type)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Incompatible type for LowCardinality column: {}", column.type->getName());
ColumnPtr indexes;
if (can_be_executed_on_default_arguments)
{
/// Normal case, when function can be executed on values' default.
indexes = low_cardinality_column->getIndexesPtr();
column.column = low_cardinality_column->getDictionary().getNestedColumn();
}
else
{
/// Special case when default value can't be used. Example: 1 % LowCardinality(Int).
/// LowCardinality always contains default, so 1 % 0 will throw exception in normal case.
auto dict_encoded = low_cardinality_column->getMinimalDictionaryEncodedColumn(0, low_cardinality_column->size());
indexes = dict_encoded.indexes;
column.column = dict_encoded.dictionary;
}
column.type = low_cardinality_type->getDictionaryType();
/// Change size of constants.
size_t num_rows = column.column->size();
for (auto & arg : args)
{
if (const auto * column_const = checkAndGetColumn<ColumnConst>(arg.column.get()))
{
arg.column = ColumnConst::create(recursiveRemoveLowCardinality(column_const->getDataColumnPtr()), num_rows);
arg.type = recursiveRemoveLowCardinality(arg.type);
}
}
return indexes;
}
Note, the s/Columns/Column in the name
There was a problem hiding this comment.
@azat addressed all three, pushed d2e2975.
-
Fold the helper (
IFunction.cpp) — done, using your rewrite: single scan-first/mutate-afterreplaceLowCardinalityColumnByNestedAndGetDictionaryIndexes(singular), returnsnullptrand leavesargsuntouched when the fast path does not apply (>1 LC column, or any non-const non-LC arg); the caller then does the full-materialization fallback. Removed the separatecanShareLowCardinalityDictionarypredicate and the extra pass. The fallback still derives the row count frominput_rows_count(the earlier bot review), the fast path from the resized nested/dictionary column. -
04489 SQL test — adopted your explanatory comment and simplified query verbatim (single
LowCardinality(String)column,concatAssumeInjective((SELECT toLowCardinality('p')), s), oneGROUP BY type). -
gtest — reduced to one essential test (
NonConstOrdinaryHeaderEval): the deterministic header-evaluation repro (input_rows_count = 0) that SQL cannot reliably reach.
Verified: gtest passes on the rebuilt binary; the 04489 SQL test passes end-to-end on a 2-shard remote('127.0.0.{1,2}', ...) server (px 4 / py 2); 10 LowCardinality/ColumnLowCardinality gtests pass.
Pre-PR validation gate (click to expand)
| # | Question | Answer |
|---|---|---|
| a | Deterministic repro? | Yes. gtest LowCardinalityDefaultImpl.NonConstOrdinaryHeaderEval constructs the inconsistent header (single LC arg + non-const ordinary arg, input_rows_count = 0) and aborts pre-fix at checkFunctionArgumentSizes. |
| b | Root cause explained? | Yes. getReturnType() wraps in LowCardinality only when <=1 non-const LC arg and every other arg constant; constness is lost across a pipeline boundary (merged aggregation key), so a function can receive more non-const LC / non-const ordinary columns at exec than the result type was derived for. |
| c | Fix matches root cause? | Yes. The single helper enforces exactly getReturnType()'s precondition (one LC column, all others constant): fast path only then; otherwise materialize all to full using input_rows_count. |
| d | Test intent preserved / new tests added? | Yes. The 04489 SQL test still exercises the distributed const-loss path; the gtest is the deterministic header-eval regression. |
| e | Both directions demonstrated? | Yes. Prior commits (0cd510e..c54c83a) established fails-without/passes-with; this is a behavior-preserving refactor — gtest + SQL test pass on the rebuilt binary (build id 7547dd5f). |
| f | Fix is general across code paths? | Yes. Single predicate covers both violations (>1 LC column, and 1 LC + non-const ordinary) in one place; no sibling path left unguarded. |
| g | Fix generalizes across inputs? | Yes. The predicate is per-column-shape (LC-ness + constness), independent of element type, so Nullable/LowCardinality(Nullable)/wrappers take the same path; recursiveRemoveLowCardinality handles nested LC on constants. |
| h | Backward compatible? | Yes. No setting/format/wire change; purely fixes a planning-time LOGICAL_ERROR. |
| i | Invariants and contracts preserved? | Yes. checkFunctionArgumentSizes sees consistent sizes on both branches; result re-wrapped as LowCardinality via the existing dictionary-building path; indexes shared only on the fast path. |
Session id: cron:clickhouse-worker-slot-0:20260714-151100
| /// A single LowCardinality argument together with a NON-constant ordinary argument, while the | ||
| /// declared result type is still LowCardinality. Reproduces the | ||
| /// "Expected the argument ... to have 0 rows, but it has 1" abort during header evaluation. | ||
| TEST_F(LowCardinalityDefaultImpl, SingleLowCardinalityWithNonConstOrdinaryHeaderEval) |
There was a problem hiding this comment.
Why do we need so much tests, I think 1 essential should be enough
|
Also the title is bad (not a lot of devs can understand what "Handle multiple LowCardinality arguments in the default function implementation" could mean), and the changelog as well, please update it according to my comments And update the description as well (you can use comments in the suggestions for the test for this) And do not forget to squash commits |
There was a problem hiding this comment.
@groeneai Write SQL tests instead of unit tests. The latter is hardly maintainable in the long run.
There was a problem hiding this comment.
The multi-LowCardinality case is now a SQL test (04489_...), which is the maintainable path and covers the main fix.
I kept one small gtest only for the complementary single-LowCardinality + non-constant-ordinary case. That one fails during query planning (input_rows_count = 0, header evaluation) and I could not build a deterministic SQL reproducer for it (~20 hand-written query shapes plus multiple QueryFuzzer runs on the unfixed binary did not trigger it - the inconsistent header needs accumulated planner/settings state). The gtest constructs that header directly, so it is the only deterministic vehicle. If you would rather drop it and rely on the SQL test alone, I am happy to remove it.
…tributed tables The default LowCardinality function implementation in IExecutableFunction::executeWithoutSparseColumns uses a fast path that strips a single LowCardinality argument to its nested dictionary and shares that column's indexes for the result. It relies on the invariant getReturnType() enforces: the result type is LowCardinality only when at most one argument is a non-constant LowCardinality column and every other argument is constant (constant arguments are converted to full before counting, so they are not counted). Constness is not preserved when blocks travel between servers. A constant argument (a LowCardinality constant, or an ordinary constant) can arrive at execution as a non-constant column, for example a constant aggregation key whose constness is dropped in the merging-aggregator header of a distributed query. The declared result type is still LowCardinality, so the fast path runs with argument sizes it was never meant to handle and aborts with a logical error (an exception in release builds, a server abort in debug and sanitizer builds), either "Default functions implementation for LowCardinality is supported only with a single LowCardinality argument" (second non-constant LowCardinality column) or "Expected the argument ... to have N rows, but it has M" in checkFunctionArgumentSizes (non-constant ordinary column). Both were reached through query planning (input_rows_count = 0) of a query of the shape concatAssumeInjective((SELECT toLowCardinality(...)), s) grouped by an injective function over a distributed table. Fold the precondition into a single scan-first/mutate-after replaceLowCardinalityColumnByNestedAndGetDictionaryIndexes: take the dictionary-sharing fast path only when there is at most one LowCardinality column and every other column is constant, otherwise return nullptr and leave the arguments intact so the caller materializes all columns to full, executes on full columns, and re-wraps the result into LowCardinality through the existing path. The fallback derives the row count from the original input_rows_count (constants are not resized on that path). The result is identical to local execution. Found by the AST fuzzer. Co-Authored-By: Claude Opus 4.8 <[email protected]>
d2e2975 to
d19ce65
Compare
|
Done, all in
The 3 inline change requests are in the same commit: folded |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 60/60 (100.00%) · Uncovered code |
…nality-default-impl Fix logical error in functions with LowCardinality arguments over distributed tables
|
Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2077 Labels added:
These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a logical error (an exception in release builds, a server abort in debug and sanitizer builds) that could happen for a function call with more than one
LowCardinalityargument over a distributed table, for exampleconcatAssumeInjective((SELECT toLowCardinality('p')), s)used as aGROUP BYkey withremote(). The messages wereDefault functions implementation for LowCardinality is supported only with a single LowCardinality argumentorExpected the argument ... to have N rows, but it has M.Description
The result type of a function over
LowCardinalityarguments isLowCardinalityonly when at most one argument is a non-constantLowCardinalitycolumn; constant arguments are not counted. Constness, however, is not preserved when blocks travel between servers, so at execution a function can receive more non-constantLowCardinalitycolumns (or non-constant ordinary columns) than its result type was derived for. The defaultLowCardinalityimplementation inIExecutableFunction::executeWithoutSparseColumnsthen ran its single-dictionary fast path with argument sizes it was never meant to handle and threw the logical error during query planning, before reading any data.Every element of the reproducer is essential to break that invariant:
concatAssumeInjective: for an injectivef,GROUP BY f(x, y)is rewritten intoGROUP BY x, yandfis re-executed on top of the aggregation (goes away withoptimize_injective_functions_in_group_by = 0).(SELECT toLowCardinality('p')): a constant of aLowCardinalitytype. As a constant it is not counted for the result type, so the result type staysLowCardinality; but unlike an ordinary-typed constant it is not folded into a literal (goes away withenable_scalar_subquery_optimization = 0), and therefore it is not eliminated from theGROUP BYkeys either - it stays a live aggregation key (compare: with(SELECT 'p')the constant key is removed and nothing fails).remote()).concatAssumeInjectiveover the merged keys then feeds two non-constantLowCardinalitycolumns into a function whose declared result type isLowCardinality.The fix folds the precondition into a single scan-first/mutate-after
replaceLowCardinalityColumnByNestedAndGetDictionaryIndexes: the dictionary-sharing fast path is taken only when there is at most oneLowCardinalitycolumn and every other column is constant. Otherwise it returnsnullptrand leaves the arguments intact, so the caller materializes all columns to full, executes on full columns, and re-wraps the result intoLowCardinalitythrough the existing path. The result is identical to local execution.Found by the AST fuzzer.
AST fuzzer (amd_debug)No related open issue found (searched for the error message, the STID, and the function name).