Skip to content

Remove false isInjective claims from MACNumToString, unhex/unbin and UUIDStringToNum - #117210

Merged
alexey-milovidov merged 5 commits into
masterfrom
fix-injective-decoding-functions
Sep 4, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
fix-injective-decoding-functions

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #117183
Closes: #117184
Closes: #117185
Related: #117137

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 wrong results for GROUP BY and uniq* over MACNumToString, unhex, unbin and
UUIDStringToNum. All four declared themselves injective, so the default-enabled
optimize_injective_functions_in_group_by and optimize_injective_functions_inside_uniq
grouped and counted by the raw argument: arguments that map onto the same result came back as
separate groups and were counted separately by uniqExact.

Description

All three functions map distinct arguments onto one result:

  • MACNumToString formats only the low 6 bytes of its UInt64 argument — the source even
    documents it, "Higher two bytes in UInt64 are just ignored" — so 2^64 inputs land on 2^48
    outputs and MACNumToString(1) = MACNumToString(1 + 0x1000000000000).
  • unhex/unbin decoding is deliberately tolerant: case-insensitive, and an incomplete leading
    group is padded. unhex('0a'), unhex('0A') and unhex('a') all decode to the same byte, and
    unbin('1010') = unbin('01010').
  • UUIDStringToNum parses case-insensitively, so the upper- and lower-case spellings of one UUID
    give the same FixedString(16).

isInjective is consumed as a proof by a growing number of default-on rewrites, so a false claim
silently changes results. Answering false can only make those rewrites decline, never fire.

Test 05059_injective_decoding_functions covers both passes for every function, plus the
partition-wise independent aggregation consumer of the same claim and the ANY OUTER JOIN to
ALL INNER JOIN rewrite in tryConvertAnyOuterJoinToInnerJoin, which peels an injective function
off the join key of the aggregated side. With the claim in place that rewrite duplicates rows: both
the ANY LEFT and the ANY RIGHT shape in the test return two rows before the fix and one after.


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

…in` and `UUIDStringToNum`

All three declared themselves injective while mapping distinct arguments onto one result:

- `MACNumToString` formats only the low 6 bytes of its `UInt64` argument, so 2^64 inputs
  land on 2^48 outputs.
- `unhex`/`unbin` decode case-insensitively and pad an incomplete leading group, so
  `unhex('0a')`, `unhex('0A')` and `unhex('a')` all give the same byte.
- `UUIDStringToNum` parses case-insensitively.

The default-enabled `optimize_injective_functions_in_group_by` and
`optimize_injective_functions_inside_uniq` then group and count by the raw argument instead
of the function result, so `GROUP BY` returned one row per colliding input and `uniqExact`
counted them separately. The same claim also feeds partition-wise independent aggregation
and `optimize_distributed_group_by_sharding_key`.

Closes: #117183
Closes: #117184
Closes: #117185
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [46555f6]

Summary: ✅


AI Review

Summary

This PR removes false isInjective claims from MACNumToString, unhex/unbin, and UUIDStringToNum, which is the right fix for the wrong-result reports behind GROUP BY and uniq*. The implementation change itself looks correct, but the evidence is still incomplete: the new ANY OUTER JOIN regression does not reliably force the join-conversion path it is supposed to protect, and another default-on wrong-result consumer of the same contract still has no focused regression.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/05059_injective_decoding_functions.sql:48-74] The new ANY OUTER JOIN cases still do not prove tryConvertAnyOuterJoinToInnerJoin is exercised. tests/clickhouse-test:1844 randomizes query_plan_convert_outer_join_to_inner_join, and if query_plan_merge_filter_into_join_condition is left random the WHERE agg.c > 0 filter can be absorbed into ON, removing the FilterStep that src/Processors/QueryPlan/Optimizations/convertOuterJoinToInnerJoin.cpp:74-192 matches. In either case the queries keep returning one row even with the old false isInjective answer, so the test can pass while missing the regression.
    Suggested fix: pin query_plan_convert_outer_join_to_inner_join = 1 and query_plan_merge_filter_into_join_condition = 0 for this section.
Tests
  • ⚠️ [tests/queries/0_stateless/05059_injective_decoding_functions.sql:4-11] Add one focused LIMIT BY regression for the same collision pattern, e.g. compare LIMIT 1 BY unhex(s) on ['0a', '0A'] with optimize_injective_functions_in_limit_by = 0. src/Analyzer/Passes/OptimizeLimitByInjectiveFunctionsPass.cpp:26-41 is default-on and rewrites the same isInjective contract, so this PR currently leaves that wrong-result surface unproved.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
  1. Pin the join settings so the ANY OUTER section actually exercises tryConvertAnyOuterJoinToInnerJoin.
  2. Add a focused regression for the default-on LIMIT BY consumer of these isInjective answers.

LLVM Coverage Report

Measured on commit 46555f6.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 8/12 (66.67%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
SELECT uniqExact(UUIDStringToNum(s)) FROM (SELECT arrayJoin(['61f0c404-5cb3-11e7-907b-a6006ad3dba0', '61F0C404-5CB3-11E7-907B-A6006AD3DBA0']) AS s);
SELECT uniqExact(UUIDStringToNum(s)) FROM (SELECT arrayJoin(['61f0c404-5cb3-11e7-907b-a6006ad3dba0', '61F0C404-5CB3-11E7-907B-A6006AD3DBA0']) AS s) SETTINGS optimize_injective_functions_inside_uniq = 0;

-- The same false claim also fed partition-wise independent aggregation.

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.

The changed isInjective contract is also consumed by tryConvertAnyOuterJoinToInnerJoin in src/Processors/QueryPlan/Optimizations/convertOuterJoinToInnerJoin.cpp:105-123, which peels wrappers from the join key before deciding it is safe to rewrite ANY OUTER into ALL INNER. A false positive there is more serious than the GROUP BY / uniq* cases: joining on MACNumToString(x) with colliding values such as 1 and 1 + 281474976710656 can duplicate rows after the rewrite instead of merely mis-grouping them.

This regression file proves GROUP BY, uniq*, and partition-wise aggregation, but it still leaves that join path untested. Please add a focused LEFT / RIGHT ANY ... JOIN case so the PR demonstrates that these functions no longer let that optimizer fire.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Added. The regression now also covers tryConvertAnyOuterJoinToInnerJoin: 05059_injective_decoding_functions.sql joins a one-row side against an aggregated side on MACNumToString(agg.x) under a filter that removes not-matched rows, in both the ANY LEFT and the ANY RIGHT orientation, and asserts one result row.

I verified the shapes are real regressions rather than merely correct queries: with the MACNumToString isInjective claim restored in a local build, both shapes return two rows (the pass peels the function off the join key, sees the aggregation key covered, and rewrites ANY OUTER into ALL INNER, so the two colliding aggregation groups both match); with the claim removed the pass declines and both return one row.

The test file also moved from 05054 to 05059, because master has taken the earlier numbers.

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.

The added join cases in tests/queries/0_stateless/05059_injective_decoding_functions.sql:53-74 still do not guarantee that tryConvertAnyOuterJoinToInnerJoin is exercised. tests/clickhouse-test randomizes query_plan_convert_outer_join_to_inner_join, and this file never pins it, so the queries can still pass with the optimizer disabled and miss the regression entirely.

Please set query_plan_convert_outer_join_to_inner_join = 1 for this section, like the existing join-conversion tests that pin it because CI may inject false.

@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

The same false-claim pattern (a fallback value shared by many inputs breaking injectivity) is still live in a few more isInjective overrides, in case you want to sweep them in the same pass: dictGetHierarchy maps every key absent from the dictionary to an empty array while claiming injectivity unconditionally (just filed #117225, reproduces at pure defaults through optimize_injective_functions_in_group_by); toFixedString (zero padding, tracked in #103686); bech32Encode (invalid input maps to an empty string, tracked in #117201); and single-argument toString of DateTime across a DST fold (tracked in #116931).

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 46555f6ab with master 6113efbf0 (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

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

Job report

…y claim

`tryConvertAnyOuterJoinToInnerJoin` peels an injective function off the join key of the
aggregated side to conclude that every row of the other side has at most one match, and then
rewrites `ANY OUTER` into `ALL INNER`. A false `isInjective` answer collapses two aggregation
groups onto one join key there, so the rewritten join duplicates rows instead of keeping the
single row `ANY` returns.

Verified against a binary with the `MACNumToString` claim restored: both the `ANY LEFT` and the
`ANY RIGHT` shape return two rows before the fix and one row after it.

The test also moves from `05054` to `05059`, because `master` has taken the earlier numbers.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and addressed the AI review's required action (a focused ANY OUTER JOIN regression, see the thread on the test file). Status of the two reds on the previous commit, both unrelated to this change:

  • Upgrade check (amd_release) — Error message in clickhouse-server.log, and the logged error is Code: 198 ... Not found address of host: aaaa… from 04725_distributed_async_insert_long_directory_name. Fleet-wide since 2026-08-31 (about 40 pull requests a day in the checks database). Fixed by Move the async distributed INSERT directory name test to the integration suite #117284, which merged into master a few hours ago and is now pulled into this branch by the base merge, so the red should clear on the next run.
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6 and 6/6) — job-level Container memory budget exceeded (/docker), no test results. Also fleet-wide (576 occurrences across 261 pull requests on 2026-08-31, falling since); @groeneai's Tear down an integration test's cluster when its module ends, not at session end #117564 addresses the cause by tearing integration clusters down per module.

The test file also moved from 05054 to 05059, because master has taken the earlier numbers.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks — agreed that they are the same pattern, but I would rather keep this pull request to the three functions its issues cover, so that each false claim is removed with its own regression and can be reverted independently if one of them turns out to be load-bearing somewhere. dictGetHierarchy (#117225), toFixedString (#103686), bech32Encode (#117201) and single-argument toString of DateTime across a DST fold (#116931) each need a different argument about which inputs collide, and the last one in particular is a time-zone-dependent claim rather than an unconditional one. I will sweep them in follow-ups against those issues.

-- `MACNumToString` ignores the two high bytes of its argument, `unhex`/`unbin` decode
-- case-insensitively and pad an incomplete leading group, and `UUIDStringToNum` parses
-- case-insensitively. None of them is injective, so the passes that eliminate an injective
-- function under `GROUP BY` or inside `uniq` must not fire for them. Every pair below prints the

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.

The changed isInjective contract is also consumed by the default-on optimize_injective_functions_in_limit_by pass (src/Analyzer/Passes/OptimizeLimitByInjectiveFunctionsPass.cpp:26-41). A false positive there returns too many rows, not just a different plan: LIMIT 1 BY unhex(s) over ['0a', '0A'] should keep one row, but with the old unhex claim the pass rewrites it to LIMIT 1 BY s and keeps both spellings.

This file proves GROUP BY, uniq*, partition-wise aggregation, and the ANY OUTER join rewrite, but it still leaves that default-on wrong-result consumer untested. Please add a focused LIMIT BY regression (for unhex, unbin, MACNumToString, or UUIDStringToNum) with the optimized and optimize_injective_functions_in_limit_by = 0 results compared.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok, though we compromise performance in favor of correctness on out-of-range values.

@alexey-milovidov alexey-milovidov self-assigned this Sep 4, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 4, 2026
Merged via the queue into master with commit 88af1b6 Sep 4, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-injective-decoding-functions branch September 4, 2026 11:42
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

3 participants