Skip to content

Normalize trailing zero bytes of String join keys compared with FixedString - #118561

Merged
vdimir merged 13 commits into
masterfrom
vdimir/join-fixedstring-string-keys
Nov 17, 2026
Merged

vdimir merged 13 commits into
masterfrom
vdimir/join-fixedstring-string-keys

Conversation

@vdimir

@vdimir vdimir commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

Closes: #116831

toFixedString('a', 3) = 'a' and toFixedString('a', 3) = 'a\0\0' are both true, but a JOIN on a FixedString and a String key cast both to String, which trims only the FixedString side. So JOIN ON x = y missed such rows, and ie_join ordered keys differently from <. Now the String key is trimmed too, and the join agrees with the comparison operators for every algorithm. Such an equality is not transitive, so the optimizations that derive predicates from join keys (transitive predicates, Cascades shuffle keys, filter copy to the other join side, join to IN) skip these key pairs via JoinCommon::isExactJoinKeyEquality, which allows only equal types, numbers, date and time types, and FixedString pairs.

Tuples are compared element-wise, so the same applies to FixedString and String elements of tuple keys at any depth, including Nullable(Tuple): the String elements are trimmed too. Arrays and maps are compared after a cast to the common type by the operators as well, so they are unchanged. isNotDistinctFrom and isDistinctFrom compared Nullable operands of these types after a cast, unlike equals; they now compare them zero-padded, also as tuple elements, so a JOIN on <=> agrees with the operator.

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 JOIN on FixedString and String key pairs, also as elements of tuple keys: values that differ only in trailing zero bytes now match and sort the same way as with the comparison operators. isNotDistinctFrom and isDistinctFrom now agree with equals for Nullable values of these types. Optimizations that derive predicates from join keys (transitive predicates, filter pushdown to the other side) no longer apply to such key pairs.

🤖 Generated with Claude Code


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

Version info

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

vdimir and others added 2 commits September 7, 2026 12:22
…String

The comparison functions compare `FixedString` with `String` as if the shorter
value were padded with zero bytes, so `toFixedString('a', 3) = 'a\0\0'` and
`toFixedString('a', 3) = 'a'` both hold. Join keys were cast to the common
supertype `String`, which drops the trailing zero bytes of the `FixedString`
side only, so `JOIN ON x = y` missed such pairs and `IEJoin` ordered them the
other way round than the `<` operator, disagreeing with the `hash` algorithm
that evaluates the same inequality as a residual filter.

Apply `trimRight(key, '\0')` to the `String` operand whenever the other
operand is a `FixedString`, in `predicateOperandsToCommonType`, so that all
join keys follow the zero-padded comparison of the operator.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [35f4237]

Summary: ✅


AI Review

Summary

Reviewed 35f4237ba3273209d462f171957a15bdb61a82b6. The change normalizes mixed FixedString/String join keys, including tuple elements, and disables optimizer rewrites that cannot preserve their equality semantics. All five added stateless tests matched their references using the current head's CI binary. No new inline findings remain after checking the existing discussion; three previously reported correctness gaps still reproduce and are retained below as explicitly deferred findings.

Findings

❌ Blockers

  • src/Processors/QueryPlan/Optimizations/convertJoinToIn.cpp:198: the new guard still admits conversions that change membership. [dismissed by author -- https://github.com/Normalize trailing zero bytes of String join keys compared with FixedString #118561#discussion_r4600270893] The author deferred this pre-existing problem; it remains real because isExactJoinKeyEquality accepts different FixedString widths, whereas IN converts the probe to the set's type instead of comparing both operands at the join's common type. With one 'a' row in each table, an ANY INNER JOIN from FixedString(5) to FixedString(3) returns 1 with query_plan_convert_join_to_in = 0 and 0 with it enabled; reproduced at the current head with runtime filters and join swapping disabled. The previously reported DateTime-to-Date conversion can conversely introduce matches by discarding the time. Cast both inputs to the comparison type before building the set, decline incompatible conversions, or link a dedicated follow-up issue. Cover both probe orientations when fixing it.

  • src/Interpreters/JoinUtils.cpp:735: accepted date/time equalities are not transitively interchangeable. [dismissed by author -- https://github.com/Normalize trailing zero bytes of String join keys compared with FixedString #118561#discussion_r4600270883] The author deferred this pre-existing problem; it remains real because one Date can equal midnight in two different time zones although those timestamps differ. Using Date '2026-11-17', 100 UTC-midnight rows and 100 Europe/Amsterdam-midnight rows, ON x = y followed by ON x = z AND y = z returns 10000 with transitive predicates enabled and 0 when disabled at the current head. The required timestamp predicate is still removable through the equivalence class. A related open issue already tracks mixed date/time equivalences and predicate synthesis: DPsub merge keys equate mixed-type columns, 3-way JOIN loses rows #130142. Exclude these pairs from transitive reasoning in that follow-up; no duplicate inline thread was opened.

  • src/Processors/QueryPlan/JoinStepLogical.cpp:1044: prepared join storages retain the original mixed-string mismatch. [dismissed by author -- https://github.com/Normalize trailing zero bytes of String join keys compared with FixedString #118561#discussion_r3949972883] Keeping prebuilt keys unchanged is an explicit compatibility decision, but the limitation remains observable: a FixedString(3) probe containing 'a' does not match a stored String key 'a\0\0' in ENGINE = Join(ANY, LEFT, y), although the scalar equality is true. This still reproduces at the current head. The direct lookup branch likewise skips normalization of stored keys; DirectJoinMergeTreeEntity::buildFilterStepWithIn still filters their raw values. Track the prepared-storage limitation separately and explicitly exclude it from the description's claim that joins agree with comparisons for every algorithm, or implement compatible lookup semantics with regression coverage.

Final Verdict

Status: ⚠️ Request changes.

The author has deliberately deferred the findings above; their existing threads were left resolved and received no duplicate replies. The minimum remaining action is to link follow-up issues for the untracked IN and prepared-storage cases and state the prepared-storage limitation in the PR description. The date/time case has the tracking issue linked above. Fixing the deferred cases in this PR is also sufficient, with focused regression tests.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 7, 2026
@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 Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 35f4237ba with master f9796e981 (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.

Object file sizes

21 object files changed (+123.45 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/JoinStepLogical.cpp.o 1.15 MiB 1.25 MiB +99.23 KiB (+8.44%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

…Keys

The join runtime filter and the shuffle of a distributed join take the keys
from `preCalculateKeys` and hash them at their least supertype. The `String`
side kept its trailing zero bytes there, so with `s JOIN fs ON s.y = fs.x` the
filter built on the cast `FixedString` value `'a'` rejected the probe row
`'a\0\0'`, and the join lost rows that the `=` operator considers equal.
`05136_join_fixed_string_zero_bytes` caught it once the randomized settings
disabled the join order optimization, which had hidden the failing orientation.

Move the zero-byte normalization into a helper shared by
`predicateOperandsToCommonType` and `preCalculateKeys`: the latter now casts
the `FixedString` side to the common type and trims the `String` side, so the
extracted keys compare byte-wise and the join step itself sees `String` keys.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
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]>
The JOIN casts both keys to their common type and compares the results.
Several optimizations assume that `=` means the same and treat a key pair
`x = y` as a plain equality: the join reorderer builds transitive
equivalence classes from it, the Cascades optimizer shuffles on it, the
filter pushdown substitutes `CAST(x, supertype)` for `y`, and a join can
be converted to `IN`. For `FixedString` vs `String` this does not hold:
`toFixedString('a', 3)` is equal to both `'a'` and `'a\0\0'`, so
`x = y AND x = z` does not imply `y = z`, and no expression of `x` is the
matched `y`. The reorderer dropped or invented `y = z`, the Cascades
shuffle sent matching rows to different nodes, the pushed-down copy of a
filter removed rows the join matches, and `IN` missed them.

Add `JoinCommon::isExactJoinKeyEquality`, which accepts only the pairs for
which the assumption holds: equal types up to `Nullable` and
`LowCardinality`, two numbers, two date or time types, or two
`FixedString`. Gate the four optimizations with it; every other pair is
declined, so new types are safe by default.

Review comments:
#118561 (comment)
#118561 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Interpreters/JoinUtils.cpp Resolved
vdimir and others added 2 commits November 9, 2026 13:18
…o inner rewrite

`isNotDistinctFrom` cast Nullable `FixedString` and `String` operands to the common type `String`,
which trims the trailing zero bytes of the `FixedString` side only, so the function disagreed with `=`
and with a JOIN on it, which normalizes such keys. Compare the nested values as `=` does.

`tryConvertAnyOuterJoinToInnerJoin` treats a GROUP BY on the join keys as proof that each row matches
at most one group, which does not hold for a `FixedString` vs `String` key pair. Skip such keys.

#118561 (comment)
#118561 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
vdimir and others added 2 commits November 11, 2026 14:52
Tuples are compared element-wise, so `tuple(toFixedString('a', 3)) = tuple('a\0\0')` is true, but a JOIN on
such keys cast both to the common type, which trims only the `FixedString` element, and missed these rows.
`predicateOperandsToCommonType` and `preCalculateKeys` now trim the `String` elements too, at any depth of
nested tuples, including `Nullable(Tuple)`. Arrays and maps are compared after a cast to the common type by
the operators as well, so they are left as is.

`isNotDistinctFrom` and `isDistinctFrom` compared `Nullable(Tuple)` operands after a cast, unlike `equals`.
They now compare such tuple elements zero-padded too, so the JOIN on `<=>` agrees with the operator.

#118561 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>

@yariks5s yariks5s 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.

I'm afraid isExactJoinKeyEquality + rejecting in some cases will affect performance. But I think it is okay considering the simplicity of the fix.

current implementation lgtm (considering the bug with tuples), but I have quick questions about nice-to-have things:

questions
  • for shuffle, could we use normalized keys instead of excluding the pair? I think we can lose valid distributed plan

  • Also I think we reject cases like tuple(uint8) vs tuple(uint16)

Comment thread src/Functions/FunctionsNullSafeCmp.h Resolved
@vdimir
vdimir added this pull request to the merge queue Nov 16, 2026
@vdimir
vdimir removed this pull request from the merge queue due to a manual request Nov 16, 2026
vdimir and others added 2 commits November 16, 2026 17:31
`Nullable` tuples with a `FixedString` vs `String` element pair are compared element by element since 107fa81. An empty tuple element then reached `FunctionComparison`, which throws `NOT_IMPLEMENTED` for zero-sized tuples. Before that commit such operands were cast to the common type and compared as whole values, which accepts an empty tuple, so the comparison returned a result.

Two empty tuples are now not distinct. This also holds without `Nullable`, where both functions threw the same exception before.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Comment thread src/Interpreters/JoinUtils.cpp Resolved
@vdimir
vdimir enabled auto-merge November 17, 2026 18:10
@vdimir
vdimir added this pull request to the merge queue Nov 17, 2026
Merged via the queue into master with commit 165c25a Nov 17, 2026
194 checks passed
@vdimir
vdimir deleted the vdimir/join-fixedstring-string-keys branch November 17, 2026 20:48
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 17, 2026
alexey-milovidov added a commit that referenced this pull request Nov 18, 2026
…g` conversion mode

#118561 added a cast of the keys to the common type in
`preCalculateKeys` (used by the runtime filters). It was built without a context, which now keeps the
trailing zero bytes of a `FixedString`, so `JOIN ... USING` with runtime filters dropped all rows
(`05334_cast_fixed_string_to_string_join_keys`). Convert the keys as `predicateOperandsToCommonType`
does: without the trailing zero bytes and under the distinct name `_CAST_strip_trailing_zeros`.

Update the tests from master that pin the old conversion:
- `05136_join_fixed_string_zero_bytes`: arrays with `FixedString` elements are now compared element by
  element, zero-padded like the scalars, so the operator and the join both give 8 instead of 4.
- `05137_join_fixed_string_zero_bytes_runtime_filter`: the new name of the key cast in `EXPLAIN`.
- `05813_parquet_fixed_string_null_as_default`: a NULL read as `String` is the default `FixedString(2)`
  converted to `String`, which now keeps its two zero bytes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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
zoomxi added a commit to zoomxi/ClickHouse that referenced this pull request Nov 19, 2026
Drop the `String`/`FixedString` cases (fixed in master by ClickHouse#118561), the `NaN`/`Tuple(Nullable)` key cases (documented per algorithm in ClickHouse#129361), and the reorder cases that repeat one query under other join or reorder algorithms. Shorten the comment of the performance test.
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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants