Skip to content

Fix logical error in functions with LowCardinality arguments over distributed tables - #108871

Merged
azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-multi-lowcardinality-default-impl
Jul 17, 2026
Merged

azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-multi-lowcardinality-default-impl

Conversation

@groeneai

@groeneai groeneai commented Jun 29, 2026 •

Copy link
Copy Markdown
Collaborator

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 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 LowCardinality argument over a distributed table, for example concatAssumeInjective((SELECT toLowCardinality('p')), s) used as a GROUP BY key with remote(). The messages were Default functions implementation for LowCardinality is supported only with a single LowCardinality argument or Expected the argument ... to have N rows, but it has M.

Description

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 (or non-constant ordinary columns) than its result type was derived for. The default LowCardinality implementation in IExecutableFunction::executeWithoutSparseColumns then 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 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.

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 one LowCardinality column and every other column is constant. Otherwise it returns nullptr and leaves 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 result is identical to local execution.

Found by the AST fuzzer.

No related open issue found (searched for the error message, the STID, and the function name).

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (d Dynamic) ENGINE=Memory; INSERT INTO t 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) GROUP BY GROUPING SETS ((type)) ORDER BY type; aborts the server every time without the fix.
b Root cause explained? getReturnType() wraps the result in LowCardinality only when at most one full (non-constant) LowCardinality argument is present; a constant LowCardinality argument is converted to full before counting and not counted. Over a distributed query the constant aggregation key loses its constness in the merging-aggregator header, so two non-constant ColumnLowCardinality columns reach the LC fast-path while the result type is still LowCardinality, and replaceLowCardinalityColumnsByNestedAndGetDictionaryIndexes raises the logical error.
c Fix matches root cause? Yes. When more than one ColumnLowCardinality reaches the fast-path, the single-shared-dictionary optimization cannot apply, so all of them are materialized to full and the result is re-wrapped into LowCardinality. This addresses the exact count mismatch, not a symptom.
d Test intent preserved / new tests added? New regression test 04489_multiple_low_cardinality_default_function_impl added (the minimized fuzzer shape over a distributed table). No existing test was weakened.
e Both directions demonstrated? Yes. The test FAILS (server abort, single LowCardinality argument logical error) on master without the fix and PASSES with correct results with the fix.
f Fix is general across code paths? Yes. replaceLowCardinalityColumnsByNestedAndGetDictionaryIndexes has exactly one caller (executeWithoutSparseColumns), which is fixed. The Variant/Dynamic adaptors set useDefaultImplementationForLowCardinalityColumns() = false and never reach this path.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified the result is wrapped correctly for LowCardinality(String) and LowCardinality(Nullable(String)) results, and that distributed output equals local output. The fix is type-agnostic (operates on ColumnLowCardinality count + recursiveRemoveLowCardinality).
h Backward compatible? (maintainer-approved exception only) Yes. No setting default, on-disk/wire format, or validation changes. The fixed path returns results identical to local execution; previously it aborted in debug/sanitizer builds.
i Invariants and contracts preserved? Yes. The result-construction path (lines after the branch) is unchanged and already handles a null indexes (the all-constant single-LC case used the same else branch). checkFunctionArgumentSizes still runs on the materialized columns. The LC result type is preserved via the existing dictionary re-wrap.

Session id: cron:clickhouse-worker-slot-1:20260629-210700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @KochetovNicolai — could you review this? The default LowCardinality function fast-path in executeWithoutSparseColumns assumes at most one ColumnLowCardinality argument, but a constant LowCardinality argument (uncounted by getReturnType()) can arrive as a non-constant column at runtime (e.g. a constant aggregation key over a distributed query), so two reach the path and trip the single LowCardinality argument logical error. The fix materializes all of them to full when there is more than one, then re-wraps the result.

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

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d19ce65]

Summary: ✅


AI Review

Summary

This PR fixes the LowCardinality default-function path so that it only reuses a shared dictionary when the runtime arguments still satisfy the same invariant that getReturnType assumed at build time; otherwise it materializes the arguments to full columns and re-wraps the result. I reviewed the current IFunction.cpp change, both added regressions, the prior PR discussion, and the latest Praktika report, and I did not find any remaining correctness, compatibility, or test-integration issues in the current head. The SQL test covers the distributed multi-LowCardinality regression, and the gtest covers the planner/header-evaluation case with a non-constant ordinary column that was not reproducible deterministically in SQL.

Final Verdict

✅ No findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 29, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed an additional commit (cf7be07) that completes this fix. The previous commit guarded only against a second LowCardinality argument reaching the single-dictionary fast path in executeWithoutSparseColumns. That is one half of the invariant getReturnType() uses to pick a LowCardinality result type:

wrap the result in LowCardinality only when there is at most one LowCardinality argument AND every other argument is constant.

The other half can also break at runtime. The fast path strips one LowCardinality column to its nested dictionary, shares its indexes, and resizes only the constant arguments to the dictionary size. A constant ordinary (non-LC) argument can arrive as a non-constant column at runtime (same mechanism: a constant key whose constness is dropped in the merging-aggregator header of a distributed query). The result type is still LowCardinality, so the fast path runs with one LC argument plus a non-constant ordinary column whose size does not match the dictionary, and aborts:

Logical error: 'Expected the argument №2 ('dynamicType(__table1.d)' of type String) to have 0 rows, but it has 1'
  checkFunctionArgumentSizes  FunctionHelpers.cpp:482
  IExecutableFunction::executeWithoutSparseColumns  IFunction.cpp

reached through planner header evaluation (input_rows_count = 0) of concatAssumeInjective((SELECT toFixedString(...)), dynamicType(d)) grouped by GROUPING SETS over a distributed table. This was found by the AST fuzzer while investigating the original concat/dynamicType family for this PR.

The > 1 LowCardinality column check is replaced with a single predicate that captures the full precondition (at most one LC column and every other column constant); otherwise all LC columns are materialized to full and the result re-wrapped through the existing path. This covers both the multiple-LC case (the original 04489 SQL test) and the non-constant-ordinary case, with one check, and produces results identical to local execution. The new case is covered by a unit test (gtest_low_cardinality_default_impl.cpp) because, unlike the multi-LC case, it could not be reproduced deterministically through SQL — only via the AST fuzzer's accumulated state or by constructing the inconsistent header sample directly.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Unit test LowCardinalityDefaultImpl.SingleLowCardinalityWithNonConstOrdinaryHeaderEval constructs the exact failing arguments (concat with result type LowCardinality(String); arg0 a non-const empty String, arg1 an empty LowCardinality(String); input_rows_count=0) and reproduces the identical error and stack on demand.
b Root cause explained? Yes. getReturnType() chooses a LowCardinality result type only when ≤1 LC argument AND 0 non-constant ordinary arguments (IFunction.cpp:750-751), at build time. The fast path in executeWithoutSparseColumns was guarded only for ≤1 LC column. At runtime a constant ordinary argument can become non-constant, so the result type is still LowCardinality but the fast path strips the single LC arg to its size-1 dictionary, resizes only constants, leaving the non-const ordinary arg at size 0 → checkFunctionArgumentSizes mismatch.
c Fix matches root cause? Yes. The new predicate canShareLowCardinalityDictionary enforces the exact invariant getReturnType() relied on (≤1 LC AND all others const). When it does not hold, fall back to full materialization. No symptom guard, no widened bounds.
d Test intent preserved / new tests added? Yes. 4 unit tests added covering: single-LC + non-const-ordinary (header eval), single-LC + non-const-ordinary (real rows, correctness), two non-const LC columns (real rows, correctness), and single-LC + const-ordinary (fast path still taken, correct + LC-encoded result). The existing 04489 SQL test (multi-LC case) is unchanged and still passes.
e Both directions demonstrated? Yes. Without the fix the header-eval test aborts with the exact LOGICAL_ERROR; with the fix all 4 tests pass. Verified by reverting/restoring the source change and rebuilding (Build ID confirmed to change).
f Fix is general across code paths? Yes. This is the single shared default-LC code path in executeWithoutSparseColumns; the predicate now covers every way the build-time invariant can be violated at runtime (extra LC column or non-const ordinary column) in one place, rather than patching one symptom.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Tested const and non-const ordinary args, single and multiple LC columns, LowCardinality(Nullable(...)) (existing 04489 query 3), and both header (size 0) and real-row execution. Correctness asserted against full execution across the matrix.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, on-disk, or wire format change. Behavior change is limited to no longer aborting on inputs that previously failed; results are identical to local/full execution.
i Invariants and contracts preserved? Yes. When the precondition holds the dictionary-sharing fast path is still taken and the result stays LowCardinality-encoded. When it does not hold, the existing convertLowCardinalityColumnsToFull + re-wrap path is used, preserving the declared LowCardinality result type and producing identical values. checkFunctionArgumentSizes now sees consistent sizes on all paths.

Session id: cron:clickhouse-worker-slot-0:20260629-223700

Comment thread src/Functions/IFunction.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

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)
# Question Answer
a Deterministic repro? Yes — gtest LowCardinalityDefaultImpl.LeadingConstWithNonConstOrdinaryHeaderEval deterministically reproduces the reviewer's header trace (concat(const String, const String, LowCardinality(String)), arg0 size-1 ColumnConst, arg1 empty non-const String, arg2 empty LowCardinality, input_rows_count=0). SQL is non-deterministic for this header class (planner builds consistent headers for hand-written queries), so the gtest is the deterministic vehicle per Phase 3 step 9.
b Root cause explained? new_input_rows_count was shared by both branches. On the fast path replaceLowCardinalityColumnsByNestedAndGetDictionaryIndexes resizes constants to the dictionary size, so front().size() is correct. On the fallback (convertLowCardinalityColumnsToFull) constants keep their original size; a leading ColumnConst (size 1) makes the row count 1 while a following non-const arg is size 0 → checkFunctionArgumentSizes aborts.
c Fix matches root cause? Yes — derives the row count per branch: input_rows_count on the fallback (matching the non-LowCardinality result branch just below), front()/dictionary size only on the fast path. No symptom guard.
d Test intent preserved / new tests added? Added 2 gtests (leading-const header-eval + real-rows). Existing 4 LowCardinalityDefaultImpl tests unchanged and still pass. No assertion weakened.
e Both directions demonstrated? Build-ID-confirmed. Buggy binary 83de6096: new header-eval test aborts Expected the argument №2 ('b' of type String) to have 1 rows, but it has 0. Fixed binary 8cb53a4e: all 6 tests pass.
f Fix is general across code paths? Yes — the row-count derivation is the single shared site for both LowCardinality-result branches; the non-LowCardinality result branch already uses input_rows_count and is unaffected. No sibling path repeats the dictionary-size derivation.
g Fix generalizes across inputs (params/datatypes/wrappers)? The bug is independent of the dictionary element type; the row-count source is the only variable. Verified correctness across single-LC, two-LC, leading-const+non-const+LC, dynamicType over Dynamic, and lower/substring/if/CAST over LowCardinality. Boundary input_rows_count=0 (header eval) and =3 both covered.
h Backward compatible? Yes — no setting, format, or behavior change. Fixes an erroneous abort; correct results are unchanged.
i Invariants and contracts preserved? checkFunctionArgumentSizes requires every non-const argument to equal new_input_rows_count. On the fallback, constants are unresized so the only valid common size is input_rows_count — the value now passed, consistent with executeWithoutLowCardinalityColumns's contract used by the non-LC branch. Fast-path invariant (dictionary size) unchanged.

Session id: cron:clickhouse-worker-slot-0:20260630-001100

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c54c83a

Finish Workflow and Mergeable Check are green. Every failure below has an owner.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Hung check failed, possible deadlock found deadlock (chronic, 565 distinct PRs / 410 master hits in 30d; unrelated to this PR's IFunction.cpp change) #101680 / #105905 (ours, open)
Stress test (arm_tsan) / Hung check failed, possible deadlock found deadlock (same family) #101680 / #105905 (ours, open)
CH Inc sync private sync CH Inc sync (not actionable by us)

Earlier-SHA failures (Build (arm_tidy) on ed18ffc, Style check on 68816ae/cf7be07) are already fixed on the current head and are not re-listed.

Session id: cron:our-pr-ci-monitor:20260630-053000

@azat azat self-assigned this Jun 30, 2026
@azat
azat added this pull request to the merge queue Jul 7, 2026
@azat
azat removed this pull request from the merge queue due to a manual request Jul 7, 2026
Comment on lines +1 to +27
-- 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;

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.

Simplify the test and explain it, why we need concatAssumeInjective(), why remote()

Suggested change
-- 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;

Comment thread src/Functions/IFunction.cpp Outdated
/// longer holds.
ColumnPtr indexes;
size_t new_input_rows_count = 0;
if (!canShareLowCardinalityDictionary(columns_without_low_cardinality))

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.

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

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.

@azat addressed all three, pushed d2e2975.

  1. Fold the helper (IFunction.cpp) — done, using your rewrite: single scan-first/mutate-after replaceLowCardinalityColumnByNestedAndGetDictionaryIndexes (singular), returns nullptr and leaves args untouched 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 separate canShareLowCardinalityDictionary predicate and the extra pass. The fallback still derives the row count from input_rows_count (the earlier bot review), the fast path from the resized nested/dictionary column.

  2. 04489 SQL test — adopted your explanatory comment and simplified query verbatim (single LowCardinality(String) column, concatAssumeInjective((SELECT toLowCardinality('p')), s), one GROUP BY type).

  3. 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)

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 do we need so much tests, I think 1 essential should be enough

@azat

azat commented Jul 14, 2026

Copy link
Copy Markdown
Member

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

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.

@groeneai Write SQL tests instead of unit tests. The latter is hardly maintainable in the long run.

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 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]>
@groeneai
groeneai force-pushed the fix-multi-lowcardinality-default-impl branch from d2e2975 to d19ce65 Compare July 14, 2026 20:15
@groeneai groeneai changed the title Handle multiple LowCardinality arguments in the default function implementation Fix logical error in functions with LowCardinality arguments over distributed tables Jul 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done, all in d19ce65:

  • Title renamed to "Fix logical error in functions with LowCardinality arguments over distributed tables".
  • Changelog entry rewritten to name the user-visible symptom (both error messages, the concatAssumeInjective(...) + remote() GROUP BY shape).
  • Description rewritten from the test explanation (why each element of the reproducer is essential).
  • 6 commits squashed into 1 (tree byte-identical, no rebuild needed; diff unchanged at 4 files, +174/-41).

The 3 inline change requests are in the same commit: folded replaceLowCardinalityColumnByNestedAndGetDictionaryIndexes (single scan-first/mutate-after, nullptr on fallback, no separate helper / second pass), simplified 04489 SQL test with the explanatory comment, and one essential gtest for the SQL-unreproducible header-eval case.

@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

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

Full report · Diff report

@azat
azat enabled auto-merge July 17, 2026 14:38
@azat
azat added this pull request to the merge queue Jul 17, 2026
Merged via the queue into ClickHouse:master with commit 100905a Jul 17, 2026
176 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 17, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…nality-default-impl

Fix logical error in functions with LowCardinality arguments over distributed tables
@watson-ch

watson-ch Bot commented Nov 10, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2077

Labels added:

  • v26.4-must-backport
  • v26.6-must-backport

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.

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 10, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 10, 2026
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants