Skip to content

Fix missing rows from JOIN runtime filter index analysis when the probe key nests a CAST - #128128

Merged
harikrishnan94 merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-join-runtime-filter-nested-cast-key
Nov 10, 2026
Merged

harikrishnan94 merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-join-runtime-filter-nested-cast-key

Conversation

@groeneai

@groeneai groeneai commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124679

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 missing rows in a JOIN whose probe-side key is a narrowing CAST of an indexed column compared with a key of a wider type, for example ON CAST(t.k AS UInt8) = d.k with d.k of type UInt64: the JOIN runtime filter pruned granules by the column value without the inner cast. Such keys are no longer used for primary key, skip index or seal-gated pruning.

Description

On 26.9.19.9 with enable_join_runtime_filters_index_analysis = 1 (the default in 26.10), SELECT count() FROM probe AS p JOIN build AS b ON CAST(p.k AS UInt8) = b.k, with probe ordered by k UInt64 (values 0..4095) and one build row b.k = 16 of type UInt64, returns 1 instead of 16. CAST(p.ts AS Date) = b.d with a DateTime build key loses rows the same way.

The analyzer unifies the key types, so the probe key becomes _CAST(CAST(k, 'UInt8'), 'UInt64'). findAppliedRuntimeFilters looked through every cast and reported the bare column k, and the read-time pruning predicate re-applies at most one cast, to the filter type (none here), so it pruned by k IN (16) instead of CAST(k, 'UInt8') IN (16). The row-level __applyFilter was correct; only the index pruning was wrong.

findAppliedRuntimeFilters now counts the casts it looks through and does not report a key under more than one. That covers every consumer: read-time primary key pruning, skip indexes and seal-gated reading. A single cast to the filter type is rebuilt exactly, so keys like UInt32 vs UInt64, Date vs DateTime, LowCardinality(String) vs String and Nullable keys keep their pruning.

Validation: the new test fails on master (20/20 randomized runs) and passes with the fix (50/50); its last arm checks that a single-cast key still prunes granules, and fails if no cast is allowed. The existing runtime filter tests behave as on master.

🤖 Generated with Claude Code


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

Version info

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

…ast keys

With `ON CAST(p.k AS UInt8) = b.k` and `b.k UInt64`, the analyzer unifies the
key types and the probe key becomes `_CAST(CAST(k, 'UInt8'), 'UInt64')`.
`findAppliedRuntimeFilters` looked through every cast and reported the bare
column `k`, while `convertRuntimeFilterToKeyConditionDAG` re-applies at most one
cast, to the filter's target type. The read-time pruning predicate was then
`k IN (16)` instead of `CAST(k, 'UInt8') IN (16)`, and every granule without the
raw value 16 was dropped. This affected read-time primary key pruning, skip
indexes and seal-gated reading, which all consume the same descriptors.

The outermost cast on the `__applyFilter` argument always has the filter's
element type, so a key under zero or one cast is rebuilt exactly. Count the
casts and do not report a key under more than one: such a key is not used for
index pruning, and the row-level filter still applies. Common type-mismatch
keys (`UInt32` vs `UInt64`, `Date` vs `DateTime`, `LowCardinality(String)` vs
`String`) carry one cast and keep their pruning.

Closes ClickHouse#124679

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (1 more nit). No blocker or major findings.

# Sev Finding Verdict Evidence / action
1 💡 The findAppliedRuntimeFilters declaration comment (actionsDAGUtils.h:13) still reads as if every CAST is looked through AGREE Noted, not blocking: the one-cast limit is documented at the implementation.
2 💡 A key under nested value-preserving casts (an explicit CAST in ON plus a key type mismatch) is no longer used for pruning AGREE Noted, not blocking: rows stay correct (the row-level filter still runs); the common mismatches (UInt32/UInt64, Date/DateTime, LowCardinality(String)/String, Nullable) carry one cast and prune as on master (512 granules considered, 510-511 dropped on both builds).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20261029-093100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's queries on master return 1 / 1 / 8 / 1 / 1 instead of 16 / 16 / 1440 / 16 / 16 (PK read-time, PK seal-gated, Date cast, minmax skip index, cast in a subquery); the new test fails 20/20 randomized runs on master.
b Root cause explained? The analyzer turns the probe key into _CAST(CAST(k, 'UInt8'), 'UInt64'). findAppliedRuntimeFilters looked through every cast and reported k; the pruning predicate re-applies only the cast to the filter type, so it pruned by k IN (16) instead of CAST(k, 'UInt8') IN (16).
c Fix matches root cause? Yes. The descriptor producer no longer reports a key under more than one cast, the only shape it cannot rebuild exactly. The row-level filter is unchanged.
d Test intent preserved / new tests added? New test 05457_join_runtime_filter_nested_cast_key: five wrong-results arms plus one arm asserting that a single-cast key still prunes granules.
e Both directions demonstrated? Yes, on binaries built from the same commit: master 20/20 FAIL with exactly the bug's diff, fix 50/50 OK with random settings and random MergeTree settings. Allowing no cast at all fails only the pruning arm (5/5).
f Fix is general across code paths? Yes. findAppliedRuntimeFilters is the single producer of the descriptors used by read-time primary key pruning, skip indexes, seal-gated reading and their copies for parallel replicas and projections. The other cast-stripping loop (RuntimeFilterExchangeWiring) only feeds the transport admission heuristic, not pruning.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked against the runtime-filters-off result: Nullable probe and build keys, signed narrowing (Int8 vs Int64), a triple cast, a multi-value build side, SEMI and ANTI joins. UInt32/UInt64, Date/DateTime, LowCardinality(String)/String and Nullable keys keep the same pruning as on master.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; only keys under nested casts stop being used for index pruning.
i Invariants and contracts preserved? A reported descriptor plus the filter type now always rebuild the probe expression exactly. The function still only appends descriptors and skips every other shape as before.

Session id: cron:clickhouse-impl-slot-7:20261029-090700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @davenger, could you review this and add the can be tested label so CI runs? findAppliedRuntimeFilters looked through every CAST around the probe key, so for _CAST(CAST(k, 'UInt8'), 'UInt64') the index pruning ran on k IN (...) without the inner narrowing cast and dropped matching granules; keys under more than one cast are now not reported for pruning.

@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0d11118]

Summary: ✅


AI Review

Summary

PR #128128 fixes missing JOIN rows by excluding probe keys with nested CAST layers from runtime-filter index pruning. The restriction applies at the shared descriptor producer, covering primary-key, skip-index and seal-gated pruning while preserving row filtering. The focused regression test passed in Fast test. No actionable findings.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Oct 29, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0d111180d with master 6f99f480f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse-keeper ×1.16 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.7 s 17.2 s +9.7 s (+130%)
Compile time of recompiled translation units

7 translation units recompiled, 10 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fd81ec3

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 05397_clickhouse_local_locked_path_untouched fails on macOS for every PR, not from this PR (its diff changes only actionsDAGUtils.cpp and its own test): the expected Another server instance in same directory is already running line is missing. 168 failures in 160 PRs since 2026-10-28 19:35 UTC, all in this job, 0 on master #128088 (mine, open)
Mergeable Check, PR praktika rollups of the row above #128088 (the owner of the row above)

CIDB has no other FAIL or ERROR row on this head; the earlier Config Workflow and Finish Workflow failures were the attempt before the can be tested label.

Session id: cron:our-pr-ci-monitor:20261029-160007

@harikrishnan94 harikrishnan94 self-assigned this Nov 5, 2026
murphy-4o added a commit to groeneai/ClickHouse that referenced this pull request Nov 6, 2026
- Drop the nested-cast flag from RuntimeFilterIndexAnalysisDescriptor: ClickHouse#128128
  leaves a key under two casts out of findAppliedRuntimeFilters for every
  reader, so the object storage read needs no special case.
- Annotate RuntimeFilterFilePruning state with TSA_GUARDED_BY, split the
  pruner emplace, rename unusable to no_pruning_predicate.
- Add the RuntimeFilterIndexAnalysisDescriptors alias.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@shankar-iyer

Copy link
Copy Markdown
Member

@groeneai Is there overlap with #129677

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Yes. Both change the same cast-stripping loop in findAppliedRuntimeFilters, and the lossy_cast check in #129677 fixes the same wrong results as #124679 (its 05495 primary_key_narrowing case is the issue's query shape). Applied to current master, the two conflict textually (2 hunks, both in that loop).

The rules differ:

So whichever lands second has to change one test: 05457 single_cast_pruned expects a single narrowing cast to prune, 05495 date_to_date_time expects a single Date to DateTime cast not to.

My suggestion: merge #128128 as the bug fix (it has v26.10-must-backport, and #128145 already depends on it), then rebase #129677 on it without lossy_cast / isValuePreservingCast. The new plus branch then needs the same casts > 1 check, because it continues before the INPUT check. If you prefer to keep the fix in #129677, say so and I will close #128128.

@harikrishnan94 harikrishnan94 left a comment

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.

LGTM

@harikrishnan94
harikrishnan94 added this pull request to the merge queue Nov 10, 2026
Merged via the queue into ClickHouse:master with commit f4435fc Nov 10, 2026
188 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 10, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 10, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 10, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 10, 2026
Backport #128128 to 26.10: Fix missing rows from JOIN runtime filter index analysis when the probe key nests a CAST
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…index analysis when the probe key nests a CAST
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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... 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.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Runtime-filter PK pruning drops rows when the join key nests a narrowing CAST

9 participants