Skip to content

Fix column count mismatch in HashJoin::getNonJoinedBlocks after join side swap - #100617

Closed
alexey-milovidov wants to merge 35 commits into
masterfrom
fix-join-column-overlap-getNonJoinedBlocks
Closed

alexey-milovidov wants to merge 35 commits into
masterfrom
fix-join-column-overlap-getNonJoinedBlocks

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 24, 2026 •

Copy link
Copy Markdown
Member

The check left_columns_count + required_right_keys.columns() + sample_block_with_columns_to_add.columns() == result_sample_block.columns() in HashJoin::getNonJoinedBlocks is too strict and triggers a LOGICAL_ERROR exception in valid scenarios:

  • After join side swapping (e.g., LEFT ANTI → RIGHT ANTI for GLOBAL NOT IN), a column name can appear in both the left block and sample_block_with_columns_to_add or required_right_keys. The result_sample_block deduplicates such overlaps, so the raw sum overshoots — this is the original STID 2980-385f exception.
  • Names can also overlap and get a qualified rename (a → t2.a) rather than deduplicating, so the result has more names than the unique set. A name-set variant of the check would break tests that exercise this case (e.g., 02497_storage_join_right_assert, where the result is [key, a, t2.a] while left ∪ right-keys ∪ columns-to-add = {key, a}).

There is no single arithmetic or set-level relationship that holds in every case. The real mapping invariant lives in the NotJoinedBlocks constructor, which already checks column_indices_left.size() + column_indices_right.size() + same_result_keys.size() == result_sample_block.columns() after actually building the index tables. That check is both necessary and sufficient for downstream code.

Drop the outer check entirely, leaving the NotJoinedBlocks check as the sole guard.

Closes #100422

CI reports:

Notes on the current CI failures (none caused by this PR):

  • Bugfix validation (functional tests) reports "Failed to reproduce the bug" for 04057_global_not_in_join_swap_column_overlap because the AST-fuzzer-generated reproducers in the test do not deterministically trigger the original STID 2980-385f exception on the inverted (master) arm_release build. The test is a smoke check that the queries run cleanly on the fixed code path — the bug it guards against is STID 2980-385f, originally observed only on amd_debug.
  • Stateless tests (amd_debug, parallel) reports 02270_errors_in_files_s3 "result differs with reference": unrelated, this is a known flaky test tracked in Flaky test: 02270_errors_in_files_s3 #104116. The url('http://localhost:11111/test/{a,tsv_with_header}.tsv') query intermittently fails to surface the URL of the missing-file error.
  • Upgrade check (amd_release) reports No stream (ba1.bin) file checksum for column b for test_3.wrong_metadata (Code: 226): unrelated, this PR does not touch part loading or column rename metadata. The narrow upgrade-check allowlist for this signature is being widened in Allowlist 02555_davengers_rename_chain upgrade-check errors #104037.
  • (Earlier runs only) Upgrade check (amd_release) reported Tuple element name 'null' is reserved ... Cannot attach table ... t_tuple_null ... (BAD_ARGUMENTS): unrelated, addressed in Allowlist Tuple element name 'null' is reserved in upgrade check #103917.
  • (Earlier runs only) Unit tests (asan_ubsan, function_prop_fuzzer): unrelated UBSan in parseDateTimeBestEffort.cpp:79 — parseDateTimeBestEffort is not touched by this PR.
  • (Earlier runs only) Stress test (arm_release) Logical error: Port is already connected in LazyUnorderedReadFromMergeTreeSource::expandPipeline (STID: 0996-327d): unrelated, addressed in Fix Port is already connected in LazyUnorderedReadFromMergeTreeSource::expandPipeline #103230.
  • (Earlier runs only) AST fuzzer (amd_debug, targeted) failure (ChunkBuffer::extractNext for ReadFromCommonBufferSource, STID 2651-2cfd): unrelated, addressed in Make correlated-subquery decorrelation joins ignore user join size limits #103322.

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 LOGICAL_ERROR exception "Unexpected number of columns in result sample block" in HashJoin::getNonJoinedBlocks that could occur with GLOBAL IN / GLOBAL NOT IN queries when the join optimizer swaps sides.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…n side swap

After join side swapping (e.g., LEFT ANTI → RIGHT ANTI for GLOBAL NOT IN),
a column name can appear in both the left block and
`sample_block_with_columns_to_add` or `required_right_keys`. There can also
be duplicates within the left block itself. The `result_sample_block`
deduplicates such columns, so the previous check that compared raw column
counts (left + right_keys + right_add) against `result_sample_block.columns()`
was too strict and triggered a LOGICAL_ERROR exception.

Replace the raw-sum check with a unique-name-set comparison that correctly
handles all deduplication cases.

Closes #100422

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100378&sha=ce356689f6a6d126e078f5cbfcbab8b3849de673&name_0=PR&name_1=AST%20fuzzer%20%28amd_tsan%29

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [29b559f]

Summary: ❌

job_name test_name status info comment
Bugfix validation (functional tests) FAIL
04057_global_not_in_join_swap_column_overlap FAIL cidb

AI Review

Summary

This PR removes a brittle column-count assertion in HashJoin::getNonJoinedBlocks and adds a regression shell test for the reported GLOBAL IN / GLOBAL NOT IN join-side-swap exception path. Based on the current code and discussion, previously raised correctness concerns are addressed and no new blocking issues were found.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Hi @alexey-milovidov, the fix direction is correct but the NameSet approach over-deduplicates. Here's why the 8 tests fail and a suggested correction.

Why the 8 Tests Fail

The 8 failing tests (00370_duplicate_columns_in_subqueries, 02497_storage_join_right_assert, etc.) contain queries with within-side duplicate column names — e.g. the same subquery column appearing twice on the left side:

SELECT 'y', * FROM (SELECT count('y'), count('y'), 2 AS x) AS t1 
RIGHT JOIN (SELECT count('x'), count('y'), 3 AS x) AS t2 ON t1.x = t2.x;

Here count('y') appears twice in t1 (left side). The result_sample_block legitimately has both columns (count: ≥5). But NameSet deduplicates count('y') to a single entry → expected_names.size() < result_sample_block.columns() → assertion fires incorrectly.

The Root Difference

  • STID 2980-385f case: expected > actual — same name in left AND right → result deduplicates cross-side → expected overcounts
  • Failing tests: expected < actual — same name twice within left → NameSet undercounts

Suggested Fix: Cross-Side Overlap Only

Instead of using NameSet for everything, subtract only the cross-side overlap (names that appear in both the left side and the right side / keys):

size_t left_columns_count = left_sample_block.columns();
if (canRemoveColumnsFromLeftBlock())
    left_columns_count = table_join->getOutputColumns(JoinTableSide::Left).size();

// Build unique name set for left side only
NameSet left_names;
if (canRemoveColumnsFromLeftBlock())
    for (const auto & col : table_join->getOutputColumns(JoinTableSide::Left))
        left_names.insert(col.name);
else
    for (const auto & name : left_sample_block.getNames())
        left_names.insert(name);

// Count names that appear in BOTH left and (right_keys ∪ to_add)
size_t cross_side_overlap = 0;
for (size_t i = 0; i < required_right_keys.columns(); ++i)
    if (left_names.count(required_right_keys.getByPosition(i).name))
        ++cross_side_overlap;
for (size_t i = 0; i < sample_block_with_columns_to_add.columns(); ++i)
    if (left_names.count(sample_block_with_columns_to_add.getByPosition(i).name))
        ++cross_side_overlap;

size_t expected_columns_count = left_columns_count
    + required_right_keys.columns()
    + sample_block_with_columns_to_add.columns()
    - cross_side_overlap;

This:

  • Preserves within-left duplicates in the count → no false positive for {count('y'), count('y'), x}
  • Correctly subtracts when the same name appears in both left and right → fixes STID 2980-385f
  • Minimal change from the original logic — just adds the overlap subtraction

alexey-milovidov and others added 2 commits March 28, 2026 16:40
The previous fix compared `expected_names.size()` (unique) against
`result_sample_block.columns()` (raw count including duplicates).
When duplicate column names exist in the result block (e.g., after
join side swap), `result_sample_block` also has duplicates, so the
comparison was still incorrect.

Compare unique name sets on both sides instead.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Mar 29, 2026
After join side swapping (e.g., LEFT ANTI → RIGHT ANTI via GLOBAL NOT IN),
column names can appear in both the left block and
sample_block_with_columns_to_add. AddedColumns correctly skips right-side
columns whose renamed name already exists in the left block, but the
assertion in getNonJoinedBlocks computed the expected column count as a
naive sum (left + right_keys + columns_to_add) without accounting for
this cross-side overlap.

The fix counts right-side columns whose renamed name appears in the left
block (matching the exact deduplication logic in AddedColumns) and
subtracts this overlap from the expected count. Unlike the NameSet-based
approach in PR ClickHouse#100617, this preserves within-left duplicate column names
which are legitimate in queries with subqueries.

Fixes STID 2980-385f — P0 recurring AST fuzzer crash hitting 20+ PRs
and master over the last 12 days.
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
alexey-milovidov and others added 16 commits April 19, 2026 08:50
… check

The previous commit constructed `NameSet result_names` from
`result_sample_block.getNames().begin()` and `.end()` — two calls to
`getNames` produce two different temporary `Names` vectors, so iterating
between iterators of different containers is undefined behaviour. In the
`fast_build` CI (debug ASan), this caused a fatal crash inside
`std::unordered_set::insert` during the regression test `02534_join_prewhere_bug`.

Store `getNames` once and construct the set from the single vector.

Also rewords the exception: the invariant is a name-set equality, not a
column count, so the message now says "Unexpected columns" and prints
the observed and expected name lists directly instead of an arithmetic
sum that was no longer meaningful after deduplication.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100617&sha=1ebb3a8182645266a98b8547d92f8b74258139fc&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous version discarded the query output with `>/dev/null 2>&1 ||:`,
so the test would have passed even if the `LOGICAL_ERROR` this PR is fixing
came back — defeating the purpose of the regression check.

Use `set -e` and a helper that captures stderr and fails the test if it
contains `LOGICAL_ERROR` or the specific `Unexpected columns in result sample
block` / `Unexpected number of columns in result sample block` messages.
Other errors (type mismatch, syntax, etc.) from these fuzzer-generated
queries are still acceptable — only the regressed exception must not reappear.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The check asserted `left_columns_count + required_right_keys.columns() +
sample_block_with_columns_to_add.columns() == result_sample_block.columns()`
— originally a raw sum, then a unique-name-set equality in this PR. Both
forms are too strict:

- Names can overlap across sides (e.g. after `LEFT ANTI → RIGHT ANTI`
  swapping for `GLOBAL NOT IN`), and `result_sample_block` deduplicates,
  so the raw sum overshoots. This was the original `STID 2980-385f`
  exception.
- But names can also overlap and get a qualified rename (`a` → `t2.a`)
  rather than deduplicating, so the result has more names than the
  unique set. The name-set variant introduced earlier in this PR broke
  `02497_storage_join_right_assert`, which exercises exactly this case:
  result is `[key, a, t2.a]` while left ∪ right-keys ∪ columns-to-add =
  `{key, a}`.

There is no single arithmetic or set-level relationship that holds in
every case. The real mapping invariant lives in the `NotJoinedBlocks`
constructor, which already checks
`column_indices_left.size() + column_indices_right.size() +
same_result_keys.size() == result_sample_block.columns()` after
actually building the index tables. That check is both necessary and
sufficient for downstream code.

Drop the outer check entirely, leaving the `NotJoinedBlocks` check as
the sole guard. Verified `04057_global_not_in_join_swap_column_overlap`,
`02497_storage_join_right_assert`, `00370_duplicate_columns_in_subqueries`,
`03993_join_no_overlapping_columns_85622`, and
`04050_join_merge_table_duplicate_columns` all pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The grep in `04057_global_not_in_join_swap_column_overlap.sh` matched any
`LOGICAL_ERROR`, which contradicts the test's stated intent of guarding only
against the original `Unexpected number of columns in result sample block`
regression. Fuzzer-style reproducers can trigger unrelated logical errors
(e.g. assertions in other components), so the broad pattern made the test
non-deterministic.

Drop `LOGICAL_ERROR` from the alternation and keep only the message-specific
patterns. The combined regex `'Unexpected (columns|number of columns) in
result sample block'` covers both historical wordings.

Addresses PR #100617 review feedback.
Aligns `.github/workflows/vectorsearchstress.yml` with the praktika source
(`runs-on: arm-large-storage`) so the `Check Workflows` job stops failing,
and restores the rerun-skip block in `create_release.yml`. These files
were previously held at the prior PR tip as a workaround for `gh` CLI
tokens lacking the `workflow` scope.
Reverts the master merge's `retry_infra_failures.yml` change so the push
does not require the `workflow` token scope. The file is byte-identical
to the previous PR tip (`d738e2ce1d6`).
…wap_column_overlap`

Add `DROP TABLE IF EXISTS temp` before the second reproducer's `CREATE TABLE temp ...` so the test stays
deterministic across local re-runs in the same server. Without this, a previous failed run that did not
reach the trailing cleanup would make the next run fail early on `Table default.temp already exists`,
masking the real regression signal.
@clickhouse-gh

clickhouse-gh Bot commented May 9, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 100.00% (5/5) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

As we can't reproduce it - closing.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The grep in `04057_global_not_in_join_swap_column_overlap.sh` matched any
`LOGICAL_ERROR`, which contradicts the test's stated intent of guarding only
against the original `Unexpected number of columns in result sample block`
regression. Fuzzer-style reproducers can trigger unrelated logical errors
(e.g. assertions in other components), so the broad pattern made the test
non-deterministic.

Drop `LOGICAL_ERROR` from the alternation and keep only the message-specific
patterns. The combined regex `'Unexpected (columns|number of columns) in
result sample block'` covers both historical wordings.

Addresses PR ClickHouse#100617 review feedback.
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: Unexpected number of columns in result sample block: A expected B ([C] = [D] + [E] + [F]) (STID: 2980-385f)

2 participants