Skip to content

Do not use mixed-type equivalence classes as DPsub merge keys - #132507

Merged
fkastrati merged 4 commits into
masterfrom
fix-dpsub-mixed-type-merge-keys
Nov 18, 2026
Merged

fkastrati merged 4 commits into
masterfrom
fix-dpsub-mixed-type-merge-keys

Conversation

@fkastrati

@fkastrati fkastrati commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #130142
Related: #128519

With query_plan_join_order_use_interesting_orders = 1, a sort-merge join planned by DPsub could lose rows when an equivalence class mixed column types, for example Date, DateTime('UTC'), and DateTime('Asia/Tokyo'). Equality across these types is not transitive.

spanningClasses returned all classes with columns on both sides of a join, without the single-type check that mergeKeyClasses has. For a join of two tables with no direct predicate, buildPhysicalPlan then added a secondary merge key from the mixed-type class (CAST(x AS DateTime('Asia/Tokyo')) = z), which the query does not imply. cleanupJoinPredicates then removed the query's own y = z as redundant.

Now spanningClasses returns only single-type classes, and mergeKeyClasses reuses it, so buildPhysicalPlan no longer synthesizes mixed-type keys. Mixed-type predicates written in the query are still applied as ordinary join conditions.

The cost follows the plan: joinKeyClasses gives mergeJoinCost and isShardedMerge all keys the merge joins on, including written mixed-type ones. A mixed-type key is joined on cast columns. If every cast is monotonic and increasing on the whole type (castsKeepOrder, the same test as the sort step), such as UInt32 to UInt64, the input order holds. buildPhysicalPlan then places the written equality at its position in the input order. Otherwise, as for Date to DateTime, the inputs are charged for sorting within their merge-key groups.

probeReadFraction no longer intersects the minmax ranges of a class of columns of different types. Those ranges are in different units (days of a Date, seconds of a DateTime), so the overlap came out near 0 and a hash join was charged almost no probe work.

The bug came with #128519 and is not in any release.

Not fixed here: Phase 2 of cleanupJoinPredicates can still synthesize a mixed-type predicate for a join that has no predicates of its own, also with interesting orders off. It is older than #128519 (it came with #98479) and needs a separate fix.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Fix wrong result of a join reordered by DPsub with query_plan_join_order_use_interesting_orders when a join key class mixed column types such as Date and DateTime in different time zones.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2722-master (included in 26.11 and later)
  • Backported to: 26.10.13.8

`spanningClasses` returned every equivalence class with columns on both
sides of a join, including classes whose columns have different types.
`buildPhysicalPlan` then added a secondary merge key from such a class
(e.g. `Date` = `DateTime('Asia/Tokyo')`), which is not implied by the query
because equality of different types is not transitive, and
`cleanupJoinPredicates` dropped the query's own predicate as redundant.
The join returned too few rows.

Restrict `spanningClasses` to single-type classes, like `mergeKeyClasses`,
so the plan and the cost in `mergeJoinCost` and `isShardedMerge` agree.

Closes: #130142
Related: #128519

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fkastrati
fkastrati requested a review from groeneai November 17, 2026 22:04
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b62cc1b]

Summary: ✅


AI Review

Summary

Reviewed b62cc1b6f12e. The change prevents DPsub from synthesizing mixed-type merge keys while retaining written predicates and accounting for their sorting costs and incompatible statistics ranges. Both previous findings are addressed. Tests 05828_dpsub_merge_keys_mixed_types and 05480_dpsub_interesting_orders pass against the PR's Fast test binary with exact reference matches. No outstanding findings.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Nov 17, 2026

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked this with the PR's CI amd_binary and the master build it was merged onto (d9849872).

  • The new test fails on master (the first query returns no rows) and passes here, so it covers the reported bug.
  • The bot's Major comes from this change. With its hints (100M rows per side, 1,000 values of k, 30,000 dates), a.k = b.k AND a.x = b.y with x Date and y DateTime('UTC') gets HashJoin on master and FullSortingMergeJoin with FinishSortingTransform on both inputs here. With y Date, both builds pick HashJoin.

Three things outside the diff:

  1. probeReadFraction has the same mixed-class problem. It intersects the key ranges of the class's columns, and those are days for a Date and seconds for a DateTime, so the overlap is 0 and the hash join is charged no probe work. With real minmax statistics and the same values on both sides, the hash join of a 3M-row fact table (sorted by DateTime('UTC')) with a 100K-row dimension costs 779,933 when the dimension's key is Date and 3,659,646 when it is DateTime('UTC'). Master gives the same numbers, so this came with #128519. Returning 1.0 (unknown) when !dpsub_data.class_single_type[order_class] would avoid it. Your call whether it goes here or separately.
  2. #128519 has v26.10-must-backport and its cherry-pick #129412 is open. This fix needs the same label, or the backport brings the wrong result to 26.10.
  3. Closes: closes #130142 on merge. The description says the Phase 2 part (cleanupJoinPredicates) stays unfixed, and I found no other issue that tracks it. Related: would keep it open.
Repro for 1
SET query_plan_optimize_join_order_algorithm = 'dpsub', query_plan_join_order_use_interesting_orders = 1, use_statistics = 1,
    allow_experimental_statistics = 1, materialize_statistics_on_insert = 1, send_logs_level = 'test';
CREATE TABLE f (y DateTime('UTC') STATISTICS(minmax, uniq), v UInt64) ENGINE = MergeTree ORDER BY y;
CREATE TABLE d_date (x Date STATISTICS(minmax, uniq), w UInt64) ENGINE = MergeTree ORDER BY w;
CREATE TABLE d_dt (x DateTime('UTC') STATISTICS(minmax, uniq), w UInt64) ENGINE = MergeTree ORDER BY w;
INSERT INTO f SELECT toDateTime('2000-01-01 00:00:00', 'UTC') + number * 300, number FROM numbers(3000000);
INSERT INTO d_date SELECT toDate('2000-01-01') + number % 10000, number FROM numbers(100000);
INSERT INTO d_dt SELECT toDateTime(toDate('2000-01-01') + number % 10000, 'UTC'), number FROM numbers(100000);
SELECT 1 FROM f JOIN d_date ON f.y = d_date.x FORMAT Null; -- costs: 779933
SELECT 1 FROM f JOIN d_dt ON f.y = d_dt.x FORMAT Null;     -- costs: 3659646

Since the previous commit `spanningClasses` returns only single-type
classes, so `mergeJoinCost` no longer saw a written key of columns of
different types, such as `a.x = b.y` with `Date` and `DateTime('UTC')`.
The plan still joins on it, so both inputs sorted only by the merge key
are sorted again, but the cost charged nothing for it and a merge join
won over a hash join.

`joinKeyClasses` gives all keys of the merge: the synthesized single-type
ones and the classes of the written predicates. `mergeJoinCost` and
`isShardedMerge` use it. A mixed-type key is joined on a cast column after
the other keys, so no input counts as sorted by all keys. The per-class
single-type flags become the bit mask `single_type_classes`.

Related: #132507 (comment)
Closes: #130142

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Nov 17, 2026
… types

`probeReadFraction` intersects the `minmax` ranges of the columns of the
merge key class. For a class of columns of different types they are in
different units, such as days of a `Date` and seconds of a `DateTime`, so
the overlap came out near 0 and a hash join was charged almost no probe
work. Return 1.0 (unknown) for such a class.

Related: #132507
Related: #130142

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

Copy link
Copy Markdown
Contributor Author

Thanks, all three points hold.

  1. probeReadFraction: reproduced with your repro on 9bf7d55 (779,933 with Date vs 3,659,646 with DateTime('UTC')). Fixed here in 261d702: it returns 1.0 (unknown) for a class of columns of different types. The same repro now gives 3,779,933 vs 3,659,646.
  2. Added v26.10-must-backport.
  3. Switched to Related:, so DPsub merge keys equate mixed-type columns, 3-way JOIN loses rows #130142 stays open for the Phase 2 part of cleanupJoinPredicates.

The bot's Major (written mixed-type keys not costed for sorting) was fixed in 9bf7d55, which came after the commit you checked.

@fkastrati

Copy link
Copy Markdown
Contributor Author

Correction to point 3 above: the description is back to Closes: https://github.com/ClickHouse/ClickHouse/issues/130142. The issue's own bug, mixed-type merge keys from #128519, is fixed here. The Phase 2 part of cleanupJoinPredicates is older: it came with #98479 (the single-type check that #122445 added covers only joins that already have a condition). It should be tracked and fixed separately.

@fkastrati
fkastrati enabled auto-merge November 17, 2026 23:22
@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b62cc1b6f with master 59e76b2ee (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 ×0.79 (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.2 s 16.2 s +10.5 s (+183%)
Compile time of recompiled translation units

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

Job report

@fkastrati
fkastrati added this pull request to the merge queue Nov 18, 2026
Since 9bf7d55 any key of columns of different types made
`mergeJoinCost` charge sorting within the groups of the merge key. A
widening cast such as `UInt32` to `UInt64` keeps the input order, so for
inputs sorted by both keys the merge needs no sorting, and the cost made a
hash join win that is slower.

`castsKeepOrder` checks, as the sort step does, that the cast of each
column to the common type of the join is monotonic and increasing on the
whole type (`Date` to `DateTime` is not). The classes whose written
equalities all pass are in `ordered_classes`, and `mergeJoinCost` counts
an input as sorted on them. `buildPhysicalPlan` places the written
equalities of such a key at its position in the input order instead of
synthesizing a key, so the plan follows the cost.

Related: #132507 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fkastrati
fkastrati removed this pull request from the merge queue due to a manual request Nov 18, 2026
@fkastrati
fkastrati enabled auto-merge November 18, 2026 01:57
@fkastrati
fkastrati added this pull request to the merge queue Nov 18, 2026
Merged via the queue into master with commit 2d82987 Nov 18, 2026
473 of 564 checks passed
@fkastrati
fkastrati deleted the fix-dpsub-mixed-type-merge-keys branch November 18, 2026 14:50
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 2026
@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 18, 2026
fkastrati added a commit that referenced this pull request Nov 25, 2026
robot-ch-test-poll added a commit that referenced this pull request Nov 25, 2026
Cherry pick #132507 to 26.10: Do not use mixed-type equivalence classes as DPsub merge keys
robot-clickhouse added a commit that referenced this pull request Nov 25, 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 25, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 25, 2026
Backport #132507 to 26.10: Do not use mixed-type equivalence classes as DPsub merge keys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-not-for-changelog This PR should not be mentioned in the changelog 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.

DPsub merge keys equate mixed-type columns, 3-way JOIN loses rows

5 participants