Skip to content

Make if with constant branches return LowCardinality - #80263

Merged
alexey-milovidov merged 164 commits into
ClickHouse:masterfrom
jh0x:jh-if
Nov 9, 2026
Merged

alexey-milovidov merged 164 commits into
ClickHouse:masterfrom
jh0x:jh-if

Conversation

@jh0x

@jh0x jh0x commented May 15, 2025 •

Copy link
Copy Markdown
Contributor

Closes: #25272

Add the opt-in optimize_if_transform_const_strings_to_lowcardinality setting. When enabled, if, multiIf, and transform infer LowCardinality(String) from constant string result branches. The default remains disabled because per-block dictionary construction can regress workloads without downstream dictionary reuse.

Also make affected consumers accept the inferred type, including IP parsing, toBool, time-zone arguments, Prometheus labels, and defaultValueOfTypeName.

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add an opt-in optimization for if, multiIf, and transform with constant string arguments to use LowCardinality.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

  • Merged into: 26.11.1.1726-master (included in 26.11 and later)

Comment thread src/Functions/if.cpp Resolved
Comment thread src/Functions/if.cpp Resolved
@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label May 15, 2025
@clickhouse-gh

clickhouse-gh Bot commented May 15, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [36137d6a]

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 16, 2025
@jh0x

jh0x commented Jun 5, 2025 •

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov it's kind of in shape in terms of compiling and tests...

But it seems that the perf test for transform slowed down. (without to enum optimisation)

Also... should this toLowCardinality behaviour be an option rather than being on by default? e.g. (optimize_if_transform_const_strings_to_lowcardinality)

@jh0x
jh0x marked this pull request as ready for review June 10, 2025 18:37
@alexey-milovidov

Copy link
Copy Markdown
Member

@jh0x, yes, it should be switchable with a setting.

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [25547bf]

Summary: ✅


AI Review

Summary

Adds opt-in LowCardinality inference for constant string branches of if, multiIf, and transform, preserves plain types for fully constant expressions, and adapts affected consumers. The disabled default addresses the previously reported evaluation cost. One new Major remains: enabling the setting breaks valid arrayFold expressions. Request changes.

Consumer coverage for the new representation:

  • The default IFunction adapters unwrap arguments and encode declared LowCardinality results; this also covers nested if, transform, and its internal executeConst call.
  • multiIf materializes conditions, recursively normalizes branches for plain results, and casts branches to the declared optimized result type. Short-circuit masks accept dictionary columns.
  • MultiIfToIfPass mirrors the setting; IfChainToMultiIfPass and the internal join-key resolver preserve their original result types.
  • IP/time-zone functions retain existing dictionary handling; toBool and dictGetOrDefault exclude unused default entries. Prometheus accepts dictionary strings and map entries; defaultValueOfTypeName extracts constant values through Field.
  • arrayReduce, joinGet, and tupleElement retain plain fully constant string arguments. Array/map constructors and accessors preserve or explicitly normalize nested dictionaries; joinGet key validation removes dictionary wrappers.
  • arrayFold preserves its accumulator type and checks exact lambda-result equality, exposing the mismatch below.
Findings

⚠️ Majors

  • src/Functions/if.cpp:1432: Inferred dictionaries violate arrayFold's accumulator contract. arrayFold((state, x) -> if(state = 'found' OR x = 'b', 'found', 'searching'), ['a', 'b'], 'searching') returns found with the setting disabled, but throws TYPE_MISMATCH when enabled: its lambda returns LowCardinality(String) while the accumulator remains String. Lambda bodies using multiIf or transform fail identically. An optimized initial accumulator with a plain String lambda result fails in the reverse direction. Normalize both sides at the fold boundary, or constrain inference so incompatible consumers retain their required representation.
Tests
  • ⚠️ Add stateless coverage for conditional/mapping expressions inside an arrayFold lambda and in its initial accumulator, with the optimization off and on. Using the PR head's Fast test binary, all four focused fold cases succeeded with the setting off and failed with TYPE_MISMATCH when enabled; nested if/multiIf controls succeeded under both settings. Existing CI is green but does not cover these folds.
Final Verdict

Status: ⚠️ Request changes. Preserve valid arrayFold execution across both settings and add regression coverage. Previously resolved findings remain addressed; no existing threads need reopening.

@jh0x

jh0x commented Jun 24, 2025

Copy link
Copy Markdown
Contributor Author

@jh0x, yes, it should be switchable with a setting.

@alexey-milovidov It has been done.

…en they are strings

The check whether the constant branches are identical materialized them as `Field` before checking
the setting and the branch types, so it affected e.g. large constant arrays even with
`optimize_if_transform_const_strings_to_lowcardinality = 0`. Compare the values only after the
branches qualify for the `LowCardinality` optimization. Also validate the arguments of `if` with
the declarative signature regardless of the optimization, so the error is the same either way.

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

Copy link
Copy Markdown
Member

🕵 Pass update: merged current master (7653564850a) with no conflicts and pushed 9bbb2b88fc9. The PR's diff against master is unchanged. clickhouse builds, and all 20 stateless tests that this PR adds or modifies pass locally on the merged tree. There are no unresolved review threads.

The two red jobs on 6acdf54df3a were unrelated and their fixes are now pulled in by the merge:

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass update: merged current master (7a1780997fc) with no conflicts and pushed e512d64cccc. The PR diff against master is unchanged. clickhouse builds, and all 20 stateless tests that this PR adds or changes pass locally on the merged tree. There are no unresolved review threads.

Comment thread src/Functions/toBool.cpp Resolved
…ity`

Disabling `useDefaultImplementationForLowCardinalityColumns` made `toBool`
on an existing `LowCardinality(UInt64)` argument expand the dictionary,
cast every row and re-encode the result, which was about 5x slower.
Use `canBeExecutedOnDefaultArguments = false` instead: the default
implementation then casts only the dictionary entries referenced by the
rows, so the unused default entry (an empty string) does not throw, while
invalid non-`NULL` values still do. Add a performance test.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=80263&sha=e512d64cccc79172de6fa975808db1ce4cb648f9&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29 (Logical error: 'ReadBuffer is canceled. Can't read from it.' in DB::ask called from ClientBase::initOutputFormat in the embedded client) and provide a fix in a separate PR. If the fix is already in progress, link it here. It looks like #128090 may cover it.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #128090 (mine, open, waiting for a review). This PR is not involved; the same abort happened twice on master (97a30be8613, 20038a78c83).

The server log of this job:

  • 05453_webterminal_close_at_binary_format_question runs SELECT number FROM numbers(10) ... FORMAT RowBinary in the web terminal at 13:45:55.066, and the embedded client waits at the binary-format question;
  • the web terminal closes at 13:45:56.072 (Closing server descriptors and waiting for client to finish);
  • at 13:45:56.073 the read of the answer in ask() fails with EIO, which cancels the input buffer;
  • at 13:45:56.076 the same thread calls ask() again on the canceled buffer: Logical error: 'ReadBuffer is canceled. Can't read from it.'.

ask() runs a second time because since #127912 a failed initOutputFormat resets the output format, and the next Data packet initializes it again. #128090 makes ask() return the default answer (no) when its input is already canceled. Its test aborts the unfixed debug build in 10 of 10 runs.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks, @groeneai. #128090 (still open) covers the ReadBuffer is canceled abort in Stateless tests (amd_debug, parallel). That leaves no failure on this PR without a tracked fix.

Pass update: merged current master (9f79cc17230) with no conflicts and pushed 385f35ba888. The PR diff against master is unchanged (56 files). clickhouse builds, and all 20 stateless tests that this PR adds or changes produce their reference output on the merged tree. There are no unresolved review threads. The PR workflow run 41155000006 was waiting on the fork-approval gate (action_required). I approved it and CI is running. The run for the previous head, 1a46dc994a1, never ran because it was never approved, so this run is also the first CI for that commit.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved

@alexey-milovidov alexey-milovidov 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.

LGTM

Comment thread src/Functions/if.cpp
auto const is_string2 = isString(arguments[2].type);
if (is_string1 && is_string2)
{
result_type = std::make_shared<DataTypeLowCardinality>(std::make_shared<DataTypeString>());

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.

[Major] Preserve the arrayFold accumulator contract for inferred LowCardinality

The consumer compatibility changes still miss arrayFold, which disables the default LowCardinality handling and requires the lambda result to exactly equal the initial accumulator type (src/Functions/array/arrayFold.cpp:90-95). Inferring the new representation inside a lambda therefore breaks an otherwise valid fold:

SELECT arrayFold(
    (state, x) -> if(state = 'found' OR x = 'b', 'found', 'searching'),
    ['a', 'b'],
    'searching')
SETTINGS optimize_if_transform_const_strings_to_lowcardinality = 1,
         optimize_if_transform_strings_to_enum = 0;

Verified with this head's Fast test binary: setting 0 returns found; setting 1 throws TYPE_MISMATCH, reporting lambda result LowCardinality(String) versus accumulator String. The same failure occurs with multiIf and transform in the lambda. There is also the reverse mismatch: SELECT arrayFold((acc, x) -> concat(acc, x), ['a'], if(number % 2, 'b', 'c')) FROM numbers(2) now has a LowCardinality(String) accumulator but a String lambda result.

Please handle this at the fold's type/representation boundary, covering both the initial accumulator and the lambda result, or restrict inference so consumers requiring the old representation keep receiving it. Add focused stateless coverage with the setting off and on.

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.

This function should be adapted separately.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 9, 2026
Merged via the queue into ClickHouse:master with commit eb580cb Nov 9, 2026
187 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 9, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 9, 2026
Master fixed `toBool` on a `LowCardinality` argument in ClickHouse#80263, so that
statement no longer fails without this PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 15, 2026
Master gained two key encoders that read a `Nullable` null-map byte as a
value, and both must agree with the rest of this PR:

- `HashedJoinKey::buildRows` (ClickHouse#129328) copies the bytes that `hash128`
  hashes, and its own contract is that every way of building a key gives
  exactly `hash128`. This PR makes `ColumnNullable::updateHashWithValue`
  hash `byte != 0`, so after the merge the copied raw byte broke that
  contract: on the merged tree `SELECT count() FROM t l JOIN t r ON l.s <=> r.s`
  over a Native null map with bytes 0, 1 and 2 aborts on the debug check
  in `buildRange` (AVX2 and NEON builds). It now copies `byte != 0`: 500
  rows, where master gives 300.
- `encodeFixedSizeKeys` (ClickHouse#124907) packs NULL into a one-bit field, so a
  byte 2 set the lowest bit of the column before it. With
  `transform_null_in = 1` and a set spilled to disk, `(0, NULL)` was found
  in `{(1, 0)}`: master 10 rows, 0 in memory. The right side is read back
  from the canonical in-memory keys, so only the probe side carried the
  raw byte.

Both are bit-identical on 0/1 maps. 05210 covers both cases, and gains
a `groupUniqArray(tuple(s))` case for the arena key encoder
(`serializeValueIntoArena`), which no case reached: reverting it left
05210 green, now it gives 3 keys where 2 are correct.

05210 also pins `optimize_if_transform_const_strings_to_lowcardinality`
to 0: the runner randomizes it since ClickHouse#80263, and with it `if` returns
`LowCardinality(Nullable(String))`, which has no `.null` subcolumn, so
the `if` case failed with UNKNOWN_IDENTIFIER on half the runs.

05211 is removed: ClickHouse#129812 made the Iceberg null count use
`countBytesInFilter`, so that reader is master's now and the merge drops
it from this PR (05211 passes on master).

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

can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Make if with constant branches to return LowCardinality.

7 participants