Skip to content

bech32Encode is not injective - #117239

Merged
alexey-milovidov merged 8 commits into
masterfrom
fix-bech32-encode-not-injective
Sep 6, 2026
Merged

alexey-milovidov merged 8 commits into
masterfrom
fix-bech32-encode-not-injective

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Closes: #117201
Related: #117210

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 LIMIT n BY over bech32Encode. The function declared itself
injective, but it returns an empty string on any encoding error, so distinct inputs that collapse
onto that result were grouped and limited as if they were distinct.

Description

bech32Encode returns an empty String (not NULL) whenever encoding fails — most easily reached
with data longer than a valid Bech32 string permits — so arbitrarily many distinct inputs share that
one output. The default-on optimize_injective_functions_in_group_by and
optimize_injective_functions_in_limit_by trusted the claim and grouped/limited by the raw argument,
returning one group (or row) per distinct argument instead of one.

bech32Decode already answers false for the analogous reason.

The same claim is also trusted by TruncateOrderByAfterGroupByKeysPass, which drops the ORDER BY
tiebreakers after an injective function of the GROUP BY keys, and by isPartitionKeyFunctionOfKeys,
which strips injective functions off the aggregation keys to aggregate each partition on its own.
Both returned wrong results too. So did StorageDistributed::getOptimizedQueryProcessingStageAnalyzer,
which strips injective functions off the GROUP BY, DISTINCT and LIMIT BY keys and, when the
sharding key remains, lets every shard complete the query on its own without a merge on the initiator.

Test 05065_bech32_encode_not_injective covers all five paths, and also checks that valid data
still round-trips.


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

On any encoding error - most easily, data too long for a valid Bech32 string - the function
returns an empty string rather than NULL, so arbitrarily many distinct inputs collapse onto
that one result. The default-on `optimize_injective_functions_in_group_by` and
`optimize_injective_functions_in_limit_by` trusted the claim and grouped or limited by the
raw argument, returning one group (or row) per distinct argument instead of one.

Closes: #117201
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ed954df]

Summary: ✅


AI Review

Summary

This PR corrects the bech32Encode function contract by marking it non-injective and extends the regression to cover the GROUP BY, LIMIT BY, ORDER BY truncation, per-partition aggregation, and analyzer-side distributed sharding-key optimizations that relied on the old claim. I did not find any remaining correctness, metadata, or evidence gaps in the current diff.

Final Verdict

✅ No findings.

LLVM Coverage Report

Measured on commit ed954df.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.10% -0.10%

Changed lines: Changed C/C++ lines covered: 1/3 (33.33%) · 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
Comment thread src/Functions/bech32.cpp Resolved
@Algunenano Algunenano self-assigned this Aug 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ed954df02 with master 7b90949ea (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, 6 s compile time in total, 7 of them have a recent master baseline.

Job report

The AI review pointed out that the `bech32Encode` injectivity claim is
consumed by more than the `GROUP BY` and `LIMIT BY` key rewrites:
`TruncateOrderByAfterGroupByKeysPass` drops the `ORDER BY` tiebreakers after
an injective function of the keys, and `isPartitionKeyFunctionOfKeys` strips
injective functions off the aggregation keys to aggregate each partition on
its own. Both returned wrong results before the fix: the tiebreaker was
truncated away, and eight partitions whose values all encode to an empty
string produced eight groups instead of one.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=117239&sha=727930f0556a9e89930f9d76881839790a3aaf52&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%205%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

Three Integration tests (amd_asan_ubsan, db disk, old analyzer, N/6) shards failed with a job-level Container memory budget exceeded (/docker) error, with no individual test failures. This PR only flips bech32Encode::isInjective to false and adds a stateless test, so it cannot affect the container memory budget of the integration test runners.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI review's finding: the new test now also covers the other two default-on planner paths that trust isInjective.

  • TruncateOrderByAfterGroupByKeysPass: GROUP BY s ORDER BY bech32Encode('bc', s), s used to be truncated to a single SORT element, dropping the s tiebreaker among the rows that encode to an empty string. The test asserts the query tree keeps both SORT nodes, with the optimize_truncate_order_by_after_group_by_keys = 0 control next to it.
  • isPartitionKeyFunctionOfKeys (independent aggregation per partition): eight rows in eight partitions that all encode to an empty string returned eight groups instead of one under allow_aggregate_partitions_independently = 1, force_aggregate_partitions_independently = 1.

Both were verified to fail before the fix and pass after it with a local build.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Not PR-caused, and all three shards resolve to fixes that are already merged: the tree that produced them predates both.

Three shards fired at 727930f0: 2/6, 5/6, 6/6. All three are check_status=error (job-level, not a test result), and the job-level row is the only failing row each one has in CIDB, with no FAILED line in any of the three logs (1141, 949 and 1189 tests passed).

The kernel records in the job logs name the breaching leaf and the victim:

shard memcg kills in oom_memcg=/docker/<dind>/docker owner
2/6 4, all task=gdb #117202
5/6 4, all task=gdb #117202
6/6 3 task=gdb, 2 task=clickhouse #117202, #117412

Neither fix was in that tree. The run's base is master 63d831df6259, which is 125 commits behind #117202's merge commit and 600 behind #117412's, and the GDB_ATTACH_LOCK that #117202 adds to tests/integration/integration-tests-entrypoint.sh reads 0 occurrences there against 6 at master. Consistent with that, the four gdb kills on 2/6 land inside 7 seconds (12:11:23 to 12:11:30), which is the unserialized attach fan-out #117202 removes, and all three jobs print the pre-#117412 sizing in their own env (CI_DIND_INIT_RESERVE=17179869184, the 16 GiB reserve #117412 replaces with a flat 8 GiB, which is what leaves the /docker leaf at 40.78 GiB instead of 48.78 GiB).

Your 117fe2db push has already dispatched a fresh run (jobs started 01:10Z) whose merge base 05514a2629 carries both: the lock is present and INTEGRATION_DIND_INIT_RESERVE = 8 * 1024**3.

After both merged the residual is one shard only. Distinct trees per shard carrying the Container memory budget exceeded (/docker) row since 2026-09-02 00:00Z, with a 90 minute ingestion guard: 1/6 0 of 453, 2/6 0 of 455, 3/6 0 of 452, 4/6 0 of 453, 5/6 0 of 452, 6/6 75 of 455.

So 2/6 and 5/6 need nothing further. The 6/6 residual is a container leak: three leaf test files declare started_cluster with scope="session" instead of scope="module", so their servers stay resident for the whole job instead of being torn down with their module. This shard ran two of the three (test_refreshable_mat_view, test_refreshable_mat_view_replicated), which matches its two task=clickhouse victims. My fix for that is open at #117564.

No separate pull request is needed from me here: every shard at that sha is owned by #117202, #117412 or #117564.

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 4, 2026
…the `bech32Encode` test

`StorageDistributed::getOptimizedQueryProcessingStageAnalyzer` strips injective functions off the
`GROUP BY`, `DISTINCT` and `LIMIT BY` keys and, when the sharding key remains, lets every shard
complete the query on its own. With `bech32Encode` wrongly marked injective, each shard emitted its
own group of the inputs that encode to an empty string. Both shards of `test_cluster_two_shards`
read the same local table, so the test asserts one group, distinct value and limited row rather
than two, with the `optimize_distributed_group_by_sharding_key = 0` controls next to it.
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 6, 2026
Merged via the queue into master with commit 6232cc8 Sep 6, 2026
175 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-bech32-encode-not-injective branch September 6, 2026 16:27
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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

Development

Successfully merging this pull request may close these issues.

bech32Encode falsely reports isInjective, producing wrong GROUP BY / LIMIT BY results when inputs collapse to the empty string

4 participants