Skip to content

Preserve comparison semantics when selecting ie_join - #129219

Closed
zoomxi wants to merge 1 commit into
ClickHouse:masterfrom
zoomxi:iejoin_fix
Closed

zoomxi wants to merge 1 commit into
ClickHouse:masterfrom
zoomxi:iejoin_fix

Conversation

@zoomxi

@zoomxi zoomxi commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

When ie_join is listed first, the planner claims two inequality conditions before extracting equality keys. The remaining equality conditions are evaluated as residual filters. This can change results because join-key comparison does not always match scalar equals:

  • join keys can match NaN values and Tuple values containing NULL, while scalar equality cannot.
  • Mixed String/FixedString comparisons also differ because scalar comparison zero-pads strings, whereas conversion to their common join-key type can lose that behavior.

Avoid preferring ie_join when demoting an equality condition would change the result, every equality condition can be converted to a valid join key, and another enabled algorithm can execute the join.

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):

Fix incorrect results when ie_join is preferred for joins whose conditions have different semantics as residual expressions and join keys.


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

`ie_join` casts a `String`/`FixedString` inequality to `String` and demotes a Tuple or Float equality to `equals`. Both disagree with join-key comparison, so another algorithm runs when one can. Cover the available-algorithm boundaries and the only-`ie_join` behavior.
@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 4, 2026
@vdimir vdimir self-assigned this Nov 4, 2026
@vdimir vdimir added the can be tested Allows running workflows for external contributors label Nov 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [32d781a]

Summary: ✅


AI Review

Summary

The PR preserves equality-key comparison semantics by declining preferred ie_join when another enabled algorithm can execute the join, and rejects mixed String/FixedString inequality keys. Two uncovered cases still produce different results by algorithm order; both were reproduced with the PR-head fast-test binary.

Findings

❌ Blockers

  • JoinStepLogical.cpp:1239: Mixed string types inside Tuple keys bypass the semantics guard. The helper only recognizes outer String/FixedString types. For tuple(l.s) = tuple(r.s) with l.s = 'a\0' of type String, r.s = 'a' of type FixedString(1), and two satisfied numeric inequalities, hash returns zero rows while ie_join,hash returns one. Inspect aligned tuple element types recursively so these equalities remain join keys.
  • JoinStepLogical.cpp:1591: Ratio-based spilling is mistaken for an unavailable grace_hash alternative. canRunGraceHash ignores max_bytes_ratio_before_external_join, although runtime selection uses the effective threshold that includes it. With max_bytes_before_external_join = 0, max_bytes_ratio_before_external_join = 0.1, matching NaN equality keys, and two satisfied inequalities, grace_hash returns one row while ie_join,grace_hash returns zero. Match the runtime spill-threshold calculation when deciding whether to preserve equality keys.
Tests
  • ⚠️ Extend the regression test with mixed String/FixedString elements inside Tuple equality keys and a grace_hash alternative configured through the ratio alone. Assert consistent results across algorithm order for both cases.
Final Verdict

Status: ❌ Block. Fix both remaining comparison-semantics gaps and add the focused regression cases above.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 4, 2026
{
const auto left = removeNullable(recursiveRemoveLowCardinality(left_type));
const auto right = removeNullable(recursiveRemoveLowCardinality(right_type));
return (isString(left) && isFixedString(right)) || (isFixedString(left) && isString(right));

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.

[P1] Check mixed string types inside Tuple equality keys

This helper only examines the outer type, so Tuple(String) versus Tuple(FixedString(1)) returns false. keyMatchesValuesEqualsRejects also returns false for these types, leaving ie_join preferred even though tuple element comparison zero-pads the strings and the common join-key conversion does not. The original result inconsistency therefore remains for compound equality keys.

On the PR-head fast-test binary, this returns 1; changing only join_algorithm to 'hash' returns 0:

SELECT count()
FROM values('s String, x Int32, y Int32', ('a\0', 1, 3)) l
ALL INNER JOIN values('s FixedString(1), x Int32, y Int32', ('a', 2, 2)) r
ON tuple(l.s) = tuple(r.s) AND l.x < r.x AND l.y > r.y
SETTINGS join_algorithm = 'ie_join,hash',
    query_plan_optimize_join_order_limit = 1,
    enable_join_runtime_filters = 0;

Compare aligned tuple element types recursively, following the scalar comparison semantics, and add this compound-key case to the regression test.

Comment on lines +1591 to +1592
const bool can_run_grace_hash = join_settings.canRunGraceHash() && strictness != JoinStrictness::Asof
&& (isInner(kind) || isLeft(kind) || isRight(kind) || isFull(kind));

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.

[P1] Recognize ratio-based spilling when checking grace_hash

canRunGraceHash checks the raw max_bytes_before_external_join and ignores max_bytes_ratio_before_external_join. Runtime algorithm selection instead uses the effective threshold, which includes the ratio. Consequently, this guard treats a runnable grace_hash alternative as unavailable and preserves the incorrect NaN result when spilling is configured through the ratio alone.

On the PR-head fast-test binary, this returns 0; changing only join_algorithm to 'grace_hash' returns 1:

SELECT count()
FROM values('f Float64, x Int32, y Int32', (nan, 1, 3)) l
ALL INNER JOIN values('f Float64, x Int32, y Int32', (nan, 2, 2)) r
ON l.f = r.f AND l.x < r.x AND l.y > r.y
SETTINGS join_algorithm = 'ie_join,grace_hash',
    max_bytes_before_external_join = 0,
    max_bytes_ratio_before_external_join = 0.1,
    query_plan_optimize_join_order_limit = 1,
    enable_join_runtime_filters = 0;

Use the same effective spill-threshold calculation as runtime selection and cover a ratio-only threshold in the regression test.

return op == JoinConditionOperator::Equals && JoinCommon::tryGetCommonSubtypeForJoinKeys(left_type, right_type) != nullptr;
}

static bool hasAlgorithmForMixedEqualityJoin(const JoinOperator & join_operator, const JoinSettings & join_settings)

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.

It's unclear why we are considering join_algorithm there if we only need to prohibit some inequalities specifically for ie_join. We could simply skip unsupported type pairs in the tryGetIEJoinKeyCondition function, so they won't be chosen as an ie join key.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

My original intention was to preserve the query results when the comparison semantics differ. But you’re right.I’ll adjust it accordingly.

}

/// `String`/`FixedString` comparison zero-pads. Their common join key is `String`, which does not.
static bool stringAndFixedStringComparisonDiffersAsJoinKey(const DataTypePtr & left_type, const DataTypePtr & right_type)

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.

By the way, I tried to support the String/FixedString combination by converting keys to String, with zero bytes padded or trimmed accordingly, and it seemed to work. However, that PR was not merged though: #118561

But ignoring such a case should be fine for now.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sounds good. I’ll wait for both #118561 and #115970 to land, then rebase and rework this PR based on the updated comparison semantics.

break;
}

if (JoinCommon::keyMatchesValuesEqualsRejects(lhs.getType())

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.

While ignoring String and Tuple(Nullable) is fine, I think supporting floats is crucial for such an algorithm, since they are a generic numeric type and probably widely used. Perhaps we can support them by extracting a NaN mask in the algorithm and handling it the same way as the null mask for Nullable types. We could also extract the null mask not only from top-level Nullable types, so that Tuple(Nullable) would work too. I can check how difficult it would be to support. Then we can decide whether to quickly follow up with float support, or maybe add a setting to keep the current behaviour.

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.

It seems I got the change slightly wrong. We already support NaN in ie_join inequality keys; the PR is really about the equality = being evaluated differently when it is executed as a residual join condition rather than as a join key. I'm not sure which behavior is the correct one. Technically, the ie_join behavior is more correct: it matches the equals function, and we should not try to mimic the hash join behavior, but rather document such non-obvious behavior for each join algorithm. I believe the same applies to the block nested loop join (it has no dedicated join_algorithm value and is executed as a last resort).

This also matches the direction we are taking elsewhere. #115970 makes hash tables, including hash join keys, agree with equals on -0.0, so after it the only float value where a join key and equals differ is NaN. There was an attempt to close that gap too, by handling NaNs in the hash join, but it turned out to be overcomplicated, and we preferred to keep this one deliberate inconsistency and document it: #106540, #112409

@groeneai check how each algorithm behaves in similar cases, i.e. where handling a JOIN ON condition as a key differs from or agrees with evaluating the same expression as a filter, check that it is documented properly (taking #115970 into account, so that -0.0 is not described as a remaining difference), and open a PR to document it where it is not.

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.

Acknowledged. I am checking, for each join algorithm, where a JOIN ON condition handled as a key differs from the same expression evaluated as a filter, and comparing that with the current docs; I will follow up here with a docs PR (or my findings) shortly.

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.

Docs PR: #129361. It adds a per-algorithm "Comparison of JOIN keys" section to the JOIN algorithms page; the JOIN statement page is left alone because #129276 rewrites it.

I measured every algorithm on master with one row on each side. As a key (direct, the hash family, the Join engine, the merge family, and the equality part of ASOF), NaN matches NaN (the hash-based ones only for the same bit pattern), and so do two (1, NULL) tuples and two NULL Variant values. As a condition (ie_join residual, block nested loop) the equality follows equals and none of them match. Two cases depend on more than the algorithm: with a non-zero max_rows_in_set_to_optimize_join, full_sorting_merge first filters each input by a set of the other side's keys that compares NaN by bits and applies only to blocks that arrive after that set is complete, so NaN values with different bit patterns matched in 16 to 29 of 50 runs; and a direct JOIN into a complex_key_direct (or complex_key_cache, complex_key_ssd_cache) dictionary with a CLICKHOUSE source sends the keys as text, where every NaN is written as nan, so only that bit pattern matches.

I left out -0.0 (#115970) and a String with trailing zero bytes against a FixedString (#118561), since those PRs remove both differences. One more case for #118561: WHERE x = y over two tables is planned as a join key (it stays a filter only for the NaN and nested NULL types), so on master it also drops the 'a\0' / toFixedString('a', 1) pair that equals accepts. The -0.0 / 0.0 pair is dropped the same way, which #115970 already covers.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You’re right—the issue is not NaN handling in IEJoin’s inequality keys, but the difference between evaluating an equality as a residual expression and comparing it as a join key.

I agree that we should not switch algorithms merely to inherit the hash join-key semantics. The remaining differences between algorithms are better made explicit
through the per-algorithm documentation in #129361.

I’ll wait for both #118561 and #115970 to land, then rebase and narrow this PR accordingly.

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 32d781a1c with master c2f3db3b0 (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.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Nov 5, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 5, 2026
Add a "Comparison of JOIN keys" section to the JOIN algorithms page and
point the `ie_join` and block nested loop sections at it.

A JOIN key is compared by the algorithm, not by `equals`. The hash
family compares `Float` keys by their bits, so a `NaN` matches only a
`NaN` with the same bit pattern; the sort-merge family compares with
`IColumn::compareAt`, where any two `NaN` are equal; both match a
`Tuple` with a `NULL` element and a `NULL` `Variant`, for which
`equals` returns `NULL`. `ie_join` evaluates a remaining equality as a
residual filter or post-join filter with `equals`, and the block nested
loop fallback evaluates the whole `ON` condition, so neither matches
those pairs.

Measured per algorithm on master (26.11.1.1) with one row on each side.
`-0.0` vs `0.0` and a `String` with trailing zero bytes vs `FixedString`
are left out on purpose: ClickHouse#115970 and ClickHouse#118561 remove those differences.
The JOIN statement page is not edited because ClickHouse#129276 rewrites it.

Related: ClickHouse#129219
Related: ClickHouse#112409

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

zoomxi commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for the review and guidance, @vdimir.
Since String/FixedString comparison in ie_join is now natively supported and covered by #118561, and the residual equals semantics when ie_join is listed first are intentional and documented in #129361, this PR is no longer needed. Closing as superseded.

@zoomxi zoomxi closed this Nov 19, 2026
@zoomxi
zoomxi deleted the iejoin_fix branch November 19, 2026 03:52
zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Nov 19, 2026
ClickHouse#129219 concluded that `ie_join` should not yield to another algorithm when a residual `equals` differs from a join key: the remaining differences (`NaN`, `NULL` inside tuples) are documented per algorithm in ClickHouse#129361, and ClickHouse#118561 makes `String`/`FixedString` keys, including `ie_join` range keys, compare like the scalar functions.

The `hash` requirement for merging ranges now states its actual reason: a merged range is a non-equi `ON` condition. Add the `String`/`FixedString` regressions from the review of ClickHouse#128140, and drop the `parallel_hash` case: `parallel_hash` is now the same algorithm as `hash`.

Related: ClickHouse#129219
Related: ClickHouse#128140
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... external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants