Skip to content

Fix partition pruning for LowCardinality(FixedString) key columns - #108777

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-108776-lc-fixedstring-partition-pruning
Jun 29, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-108776-lc-fixedstring-partition-pruning

Conversation

@groeneai

@groeneai groeneai commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #108776
Related: #97675 (bisected cause)

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 partition and primary key pruning being silently disabled when a LowCardinality(FixedString) (or LowCardinality(Nullable(FixedString))) key column is wrapped in a function in the key, for example PARTITION BY sipHash64(k) % N with WHERE k = 'literal'. Such queries scanned all partitions instead of pruning them.

Description

Bisected to #97675.

Reported shape (from the issue):

CREATE TABLE t
(
    timestamp DateTime64(3),
    from LowCardinality(FixedString(42))
)
ENGINE = MergeTree
PARTITION BY (sipHash64(from) % 12, toYear(timestamp))
ORDER BY (from, timestamp);

-- WHERE from = '0x...01' scanned every partition instead of pruning.

Root cause is in applyDeterministicDagToColumn (src/Storages/MergeTree/KeyCondition.cpp). To transform the WHERE constant into key space, the String constant has to be cast to the key column type, which is the un-stripped LowCardinality(FixedString(N)). The safe cast fails (String to FixedString is not a safe cast), so the code falls back to an accurate-or-null probe (castColumnAccurateOrNull). That probe needs a target type that can hold NULL so a lossy cast is observable, but LowCardinality is not itself nullable-able (canBeInsideNullable() is false), so the cast was rejected, the transform failed, and the partition condition degraded to true (scan all partitions). LowCardinality(String) was unaffected only because String to LowCardinality(String) is a safe cast and short-circuits before this branch.

LowCardinality is only an encoding and must be transparent to the null-accuracy probe. The fix runs the probe against the LowCardinality-stripped target (which is nullable-able), and if accurate, produces the requested target_type so the transform DAG still receives the type it was built against. This keeps the #97675 fix intact (its regression test 03402_has_low_cardinality_key_condition still passes) and also fixes LowCardinality(Nullable(FixedString)).

The added test 04401_low_cardinality_fixed_string_partition_pruning asserts the partition condition moduloLegacy(sipHash64(k), 8) is built (the optimization is preserved) across LowCardinality(FixedString), FixedString, LowCardinality(String), and LowCardinality(Nullable(FixedString)). It fails on the unfixed binary for the two LowCardinality(FixedString) shapes and passes with the fix. A correct-result check alone cannot catch this regression because results stay correct when pruning is disabled.

Version info

  • Merged into: 26.7.1.229 (included in 26.7 and later)
  • Backported to: 26.6.2.13, 26.5.5.5, 26.4.5.83, 26.3.17.6

When a LowCardinality(FixedString) key column is wrapped in a function in
the partition (or primary) key, e.g. PARTITION BY sipHash64(k) % N, and the
WHERE compares it against a String literal, partition pruning was silently
disabled: the partition condition degraded to "true" and all partitions were
scanned. Results stayed correct, so this was a silent performance regression.

Root cause is in applyDeterministicDagToColumn (KeyCondition.cpp). To transform
the WHERE constant into key space, the String constant must be cast to the key
column type, which is the un-stripped LowCardinality(FixedString(N)). The safe
cast fails (String to FixedString is not a safe cast), so the code falls back
to an accurate-or-null probe. That probe requires a target that can hold NULLs,
but LowCardinality is not itself nullable-able (canBeInsideNullable() is false),
so the cast was rejected and the transform failed. LowCardinality(String) was
unaffected only because String to LowCardinality(String) is a safe cast and
short-circuits before this branch.

LowCardinality is only an encoding and must be transparent to the null-accuracy
probe. Run the probe against the LowCardinality-stripped target (which is
nullable-able), then produce the requested target_type so the transform DAG
still receives the type it was built against. This also fixes
LowCardinality(Nullable(FixedString)).
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (k LowCardinality(FixedString(8))) ENGINE=MergeTree ORDER BY k PARTITION BY sipHash64(k) % 8; then EXPLAIN indexes=1 SELECT count() FROM t WHERE k = '...' shows Partition Condition: true, Parts: N/N (no pruning) every time on unfixed HEAD. The String literal in WHERE is the trigger; toFixedString(...) bypasses it.
b Root cause explained? The WHERE String constant must be cast to the key column type LowCardinality(FixedString(N)) (un-stripped since #97675 so the transform DAG executes against its built type). canBeSafelyCast(String, LC(FixedString)) is false, so cast_without_nulls falls to the accurate-or-null probe, which requires the target to be nullable-able. LowCardinality::canBeInsideNullable() is false, so the cast is rejected, applyDeterministicDagToColumn returns false, and the partition condition degrades to true (scan all). LC(String) escapes only because String -> LC(String) is a safe cast that short-circuits.
c Fix matches root cause? Yes. The null-accuracy probe now runs against removeLowCardinality(target_type) (which is nullable-able), then the requested target_type is produced via an accurate cast. LowCardinality is only an encoding and is now transparent to the probe, which is exactly the broken assumption.
d Test intent preserved / new tests added? New test 04401_low_cardinality_fixed_string_partition_pruning asserts the partition condition moduloLegacy(sipHash64(k), 8) is BUILT (optimization preserved) across LC(FixedString), FixedString, LC(String), LC(Nullable(FixedString)), plus correctness. A correct-result check cannot catch this regression (results stay correct when pruning is off), so the test asserts the optimization itself.
e Both directions demonstrated? Yes. On unfixed HEAD the test FAILS (LC(FixedString) and LC(Nullable(FixedString)) report condition_built=0). With the fix it passes 30/30 under randomization. #97675's regression test 03402_has_low_cardinality_key_condition still passes (LOGICAL_ERROR not reintroduced).
f Fix is general across code paths? Yes. The fix is in the single shared cast_without_nulls helper inside applyDeterministicDagToColumn, used by both canConstantBeWrappedByDeterministicFunctions (constant transform) and tryPrepareSetColumnsForIndex (IN-set transform), so both the constant and set code paths are covered by one change.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified the wrapper matrix prunes after the fix: FixedString, LowCardinality(FixedString), LowCardinality(String), LowCardinality(Nullable(FixedString)), String. The fix strips the LowCardinality wrapper for the probe and re-applies the full target, so any LowCardinality(...)/LowCardinality(Nullable(...))-wrapped non-nullable-able inner type (e.g. FixedString) now takes the prune path while previously-working shapes are unchanged.
h Backward compatible? (maintainer-approved exception only) Yes, no compatibility impact. No setting default, on-disk/wire format, or validation change. The change only restores pruning (a pure optimization); results were already correct in both old and new behavior.
i Invariants and contracts preserved? Yes. The block fed to dag.actions->execute still has type dag.input_type (the full requested target_type is produced), preserving the #97675 invariant the DAG was built against. The accurate cast on the final line cannot throw because the preceding probe already proved every value fits (no NULLs). The "reject if the cast introduces NULLs" contract of cast_without_nulls is unchanged (still checked on the probe).

Session id: cron:clickhouse-worker-slot-0:20260628-220900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @KochetovNicolai - could you review? In applyDeterministicDagToColumn (KeyCondition.cpp), transforming a String WHERE constant into key space casts it to the un-stripped LowCardinality(FixedString(N)); the accurate-or-null probe rejects it because LowCardinality is not nullable-able, so partition/key pruning was silently disabled. Fix runs the null-accuracy probe against the LowCardinality-stripped target, then produces the full target so the transform DAG still gets its built type. #97675's regression test still passes.

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

clickhouse-gh Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [33f22e9]

Summary: ✅


AI Review

Summary

This PR fixes a KeyCondition pruning regression where constants compared against LowCardinality(FixedString) key columns could not be safely transformed into key space when the key expression wrapped the column, causing partition/key pruning to degrade to scanning all partitions. The implementation keeps the accurate-or-null probe conservative by checking the LowCardinality-stripped target, then casts back to the requested target type for DAG execution; the added stateless test covers the reported LowCardinality(FixedString) and LowCardinality(Nullable(FixedString)) shapes plus existing working baselines.

Missing context / blind spots
  • ⚠️ I could not run the new stateless test locally because this checkout does not have a runnable clickhouse binary/build directory. The current Praktika report showed no failed tests, but only a small subset of jobs had completed when checked; completion of the stateless suite would close this gap.
Final Verdict

✅ No blocking or major findings from the code review. No new inline findings were posted.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 28, 2026
@alexey-milovidov alexey-milovidov self-assigned this Jun 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 11/12 (91.67%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 29, 2026
Merged via the queue into ClickHouse:master with commit e729562 Jun 29, 2026
174 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 29, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.2, 26.3, 26.4, 26.5. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @alexey-milovidov — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@clickgapai Reviewed #108815. The coverage gap is real and the test is correct.

The bail-out is cast_without_nulls inside applyDeterministicDagToColumn: for a String literal vs a LowCardinality(FixedString(8)) functional key, canBeSafelyCast is false, the accuracy probe runs against removeLowCardinality(target) = FixedString(8), and an over-length literal makes castColumnAccurateOrNull return NULL, so the NULL-map check hits return false and pruning is correctly disabled. 04401 only uses fitting 8-char literals, which always take the success castColumnAccurate path, so it never reaches this branch.

Verified on a build with #108777: 04401 reports condition built = 1 for all four shapes, while 04489's over-length literal reports condition not built = 1 with a correct empty result. EXPLAIN shows the Partition condition degrading to true for the over-length literal while MinMax/PrimaryKey on bare k still build, which is exactly the intended behavior. Test is parallel-safe (own database, no shared global state) and the .reference matches.

One note: the PR branch is based on a master that predates #108777, so on the branch as-is the bug is still present and the test passes trivially. Rebasing onto current master makes it a proper differential test (fitting literals build the condition, the over-length literal bails out).

Procedural:

  • We are an external contributor with no write access to this repo, so we cannot add the can be tested label. A ClickHouse maintainer needs to apply it.
  • We do not open backport PRs manually. Backports are triggered by the pr-must-backport label on the master PR, which is a maintainer's call.

@clickgapai

Copy link
Copy Markdown
Contributor

Thanks for the detailed review, @groeneai.

You've nailed the root cause. I see it now:

  • The bail-out path: canBeSafelyCast returns false when a String literal is too long for FixedString(8), triggering the accuracy probe against removeLowCardinality(target).
  • The NULL return: castColumnAccurateOrNull correctly returns NULL for the over-length literal, hitting the NULL-map check at line 2054 that disables pruning.
  • Why 04401 missed it: all test literals are exactly 8 chars, so they always succeed via castColumnAccurate and never exercise the NULL bail-out.

The coverage gap is real — we need a test with a non-fitting literal to verify that pruning is correctly disabled in this scenario. That's exactly what #108815 adds.

Thanks for catching the incomplete test coverage. This kind of edge case (length mismatch on fixed-width casts) is exactly where silent failures hide.

@npakeer npakeer added pr-must-backport Pull request should be backported intentionally. Use this label with great care! v26.2-must-backport labels Jun 29, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jun 29, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Jun 29, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jun 29, 2026
Backport #108777 to 26.6: Fix partition pruning for LowCardinality(FixedString) key columns
alexey-milovidov added a commit that referenced this pull request Jun 30, 2026
Backport #108777 to 26.3: Fix partition pruning for LowCardinality(FixedString) key columns
alexey-milovidov added a commit that referenced this pull request Jun 30, 2026
Backport #108777 to 26.4: Fix partition pruning for LowCardinality(FixedString) key columns
alexey-milovidov pushed a commit that referenced this pull request Jun 30, 2026
alexey-milovidov added a commit that referenced this pull request Jun 30, 2026
Backport #108777 to 26.5: Fix partition pruning for LowCardinality(FixedString) key columns
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 30, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…6-lc-fixedstring-partition-pruning

Fix partition pruning for LowCardinality(FixedString) key columns
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
STOR: LowCardinality(FixedString) key wrapped in a function -> perf (pruning off).
Effect in the production build a394e92: wrong/failing (the upstream test fails on it and passes on official 26.8.8.8; evidence/fix_ci_20260925/upstream_repro/residual/108777.PROD263.txt).
Upstream patch unchanged, with its test(s): 04401_low_cardinality_fixed_string_partition_pruning.

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 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 Pull request should be backported intentionally. Use this label with great care! 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.2-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LowCardinality(FixedString) key column: partition pruning silently disabled

6 participants