Skip to content

Fix column count assertion in HashJoin::getNonJoinedBlocks - #101066

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix/hashjoin-column-overlap-assertion
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix/hashjoin-column-overlap-assertion

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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 to CHANGELOG.md):

Fix Logical error: Unexpected number of columns in result sample block crash in HashJoin::getNonJoinedBlocks when column names overlap between left and right sides after join side swapping (e.g., with GLOBAL NOT IN).

Description

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. During joinBlock, AddedColumns correctly skips right-side columns whose renamed name already exists in the left block (see AddedColumns constructor, line 154 of AddedColumns.h). However, 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, causing a LOGICAL_ERROR crash.

Root cause: The assertion at line 1711 of HashJoin.cpp assumed result_sample_block.columns() == left_columns_count + required_right_keys.columns() + sample_block_with_columns_to_add.columns(), but when column names overlap across sides, the result block has fewer columns because AddedColumns deduplicates them.

Fix: Count right-side columns (from both sample_block_with_columns_to_add and required_right_keys) whose renamed name appears in the left block, matching the exact deduplication logic in AddedColumns, and subtract this overlap from the expected count.

Why not PR #100617's approach: That PR uses NameSet comparison which also deduplicates within-left duplicates. Queries with subqueries can legitimately produce duplicate column names on the same side (e.g., __table2 appearing twice in the left block). The NameSet approach causes expected_names.size() < result.columns() for such queries, breaking 7 existing join tests (00577, 03707, 02497, 02267, 00217, 02381, 00370). Our cross-side overlap approach preserves within-left duplicates while correctly handling cross-side overlap.

Impact: STID 2980-385f — P0 recurring AST fuzzer crash hitting 20+ unrelated PRs and master over the last 12 days.

Verification:

  • New regression test 04068_hashjoin_column_overlap_assertion — 20/20 passes with randomization
  • All 6 locally-runnable join-duplicate tests pass 60/60 (10 runs each)
  • The 7th test (00217) requires remote shards unavailable locally but is structurally unaffected

🤖 Generated with Claude Code

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (Session: cron:clickhouse-ci-task-worker:20260329-091500)

a) Deterministic repro? Yes — the AST fuzzer queries from PR #100617's test (GLOBAL NOT IN with join side swap) trigger the LOGICAL_ERROR assertion deterministically in debug builds without the fix.

b) Root cause explained? getNonJoinedBlocks assertion at line 1711 computes expected = left_columns + required_right_keys + columns_to_add without subtracting cross-side overlap. When AddedColumns (line 154 of AddedColumns.h) skips right-side columns whose renamed name exists in the left block, the actual result has fewer columns than the naive sum, causing expected != result → LOGICAL_ERROR.

c) Fix matches root cause? Yes — the fix mirrors the exact AddedColumns deduplication logic: builds a NameSet from left column names, counts right-side columns (from both sample_block_with_columns_to_add and required_right_keys) whose renamedRightColumnName appears in the left set, and subtracts this overlap from the expected count.

d) Test intent preserved? Yes — the assertion still checks exact column count equality. No bounds widened, no tags added, no assertions removed. The only change is correct accounting for cross-side overlap.

e) Both directions demonstrated? Test passes 20/20 with fix. All 6 locally-runnable join-duplicate tests (00577, 03707, 02497, 02267, 02381, 00370) that PR #100617 breaks pass 60/60 with this fix.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @KochetovNicolai — could you review this? It fixes the P0 recurring STID 2980-385f crash in HashJoin::getNonJoinedBlocks by correctly accounting for cross-side column name overlap after join side swapping, using a targeted overlap count instead of the NameSet deduplication approach in #100617 (which breaks 7 join-duplicate tests).

@pufit pufit added the can be tested Allows running workflows for external contributors label Mar 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0ec03d1]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Trying to extract chunk from ChunkBuffer before all inputs are finished (unfinished inputs: A) (STID: 2651-2cfd) FAIL cidb
Bugfix validation (functional tests) FAIL
04068_hashjoin_column_overlap_assertion FAIL cidb

AI Review

Summary

This PR fixes a HashJoin::getNonJoinedBlocks column-count assertion mismatch when right-side column names overlap with left-side names after join-side rewriting, and adds a regression test for that scenario. I did not find any additional correctness, safety, or performance issues in the current diff.

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 29, 2026
<= toInt64(materialize(9223372036854775807))
FORMAT Null
SETTINGS enable_analyzer = 1
" 2>&1 | grep -v -c 'LOGICAL_ERROR' > /dev/null

@clickhouse-gh clickhouse-gh Bot Mar 29, 2026 •

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.

This check is not reliable for detecting LOGICAL_ERROR.

grep -v -c 'LOGICAL_ERROR' > /dev/null succeeds whenever there is any non-matching line, so a real LOGICAL_ERROR can be masked by other stderr lines (for example Received exception from server/query context lines).

Please make this assertion explicit, e.g.:

... 2>&1 | grep -q 'LOGICAL_ERROR' && exit 1
# or
... 2>&1 | (! grep -q 'LOGICAL_ERROR')

The same pattern appears again below in this file.

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.
- Replace NameSet::count() with NameSet::contains() for membership checks
  (clang-tidy readability-container-contains diagnostic)
- Fix test assertion: use `{ ! grep -q 'LOGICAL_ERROR'; }` instead of
  `grep -v -c 'LOGICAL_ERROR' > /dev/null` which could mask LOGICAL_ERROR
  presence when other stderr lines exist
@vdimir

vdimir commented Apr 7, 2026

Copy link
Copy Markdown
Member

@groeneai create minimal repro

@groeneai

groeneai commented Apr 7, 2026

Copy link
Copy Markdown
Collaborator Author

@vdimir Minimal repro (crashes the server with LOGICAL_ERROR on current master):

SELECT 1 FROM numbers(1)
WHERE number >= CAST((SELECT number), 'Int64')
  AND number <= 0
SETTINGS enable_analyzer = 1;
Logical error: 'Unexpected number of columns in result sample block:
  2 expected 3 ([__table2, __table1.number] = [__table2] + [__table1.number] + [__table2])'

What happens: CAST around a correlated scalar subquery (SELECT number) prevents the analyzer from inlining it, forcing a join. Combined with the second condition (AND number <= 0), the planner produces a join where __table2 (the subquery result column) appears in both left_sample_block and sample_block_with_columns_to_add. During joinBlock, AddedColumns correctly skips the duplicate (HashJoin/AddedColumns.h:154 — if (!left_block.has(qualified_name))), but the assertion in getNonJoinedBlocks (HashJoin.cpp:1711) uses the naive sum left + right_keys + columns_to_add without subtracting this cross-side overlap, so it fires.

Variants also crash (from recent AST fuzzer findings in CIDB, simplified):

-- Table with correlated subquery in WHERE (CIDB 2026-04-03, PR #99736)
CREATE TABLE t (a Int32, b String) ENGINE = MergeTree ORDER BY a;
INSERT INTO t VALUES (1, 'x'), (42, 'y');
SELECT * FROM t
WHERE b <= (SELECT if(a > 2, b, 'z'))
  OR (a = 42)
SETTINGS enable_analyzer = 1;

All share the same root cause: correlated subquery producing a __table2 column that overlaps with the left block after the analyzer's join planning.

@groeneai

groeneai commented Apr 7, 2026

Copy link
Copy Markdown
Collaborator Author

Correction on the second variant — the CAST wrapping is what triggers the overlap. The same pattern works on any table:

CREATE TABLE t (a Int32, b String) ENGINE = MergeTree ORDER BY a;
INSERT INTO t VALUES (1, 'x'), (42, 'y');
SELECT 1 FROM t WHERE a >= CAST((SELECT a), 'Int64') AND a <= 42 SETTINGS enable_analyzer = 1;
-- crashes with: Unexpected number of columns in result sample block: 2 expected 3
--   ([__table2, __table1.a] = [__table2] + [__table1.a] + [__table2])

The common trigger across all AST fuzzer findings: CAST (or equivalent type-casting expression) wrapping a correlated scalar subquery, combined with a second filter condition on the same column, under enable_analyzer = 1.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Update 2026-04-19 — bug status on master and PRs

CIDB status (last 14 days)

Window Master failures PR failures
Last 14 days (since Apr 5) 0 3
Since April 9 0 0

Master has been clean for 20+ days (last hit 2026-03-30 on commit 92311943). All PR tracks have been clean for 10+ days.

Merged upstream fixes

Two PRs fixed the bug at upstream call sites:

These two cover most patterns. However, two AST fuzzer failures on April 7-8 happened on branches that already contain BOTH merged fixes (PR #100276 commit 9191725739d8, PR #102121 commit 0839f6a09d95):

PR #100276:  [__table2, __table1.i]         = [__table2] + [__table1.i] + [__table2]
PR #102121:  [exists(__table2), __table1.c0] = [exists(__table2)] + [__table1.c0] + [exists(__table2)]

Both show the same pattern my PR addresses: a name appears in BOTH left_sample_block and sample_block_with_columns_to_add. The upstream fixes did not cover these paths (correlated subqueries wrapped in EXISTS or used inside convert_query_to_cnf = 1 conditions).

Why my PR is still needed

My defensive fix at the assertion site would catch these uncovered cases. Its logic:

  • Build left_names set
  • Count right-side columns (from sample_block_with_columns_to_add ∪ required_right_keys) whose renamedRightColumnName appears in left_names
  • Subtract from the expected sum

For the two uncovered cases:

Ask

@vdimir @KochetovNicolai @alexey-milovidov — could you take another look? The PR is mergeable, 142/163 CI checks pass, 1 failure is a known flaky test_backup_restore_s3 unrelated to the change (issue #90662).

Minimal repro (provided on Apr 7) — now passes on current master due to PR #98286's upstream fix, but the fuzzer findings above show PR branches still hit the pattern:

SELECT 1 FROM numbers(1)
WHERE number >= CAST((SELECT number), 'Int64')
  AND number <= 0
SETTINGS enable_analyzer = 1;

Session: cron:clickhouse-ci-task-worker:20260419-014500

@clickhouse-gh

clickhouse-gh Bot commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.10% +0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 85.71% (18/21) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented May 9, 2026

Copy link
Copy Markdown
Collaborator Author

Closing this PR — the original bug (STID 2980-385f) is no longer reproducible on master.

Verification on current master (commit 9ed0cd6, 2026-05-09):

  • April 7 minimal repro:
    SELECT 1 FROM numbers(1)
    WHERE number >= CAST((SELECT number), 'Int64')
      AND number <= 0
    SETTINGS enable_analyzer = 1;
    → returns 1, no LOGICAL_ERROR.
  • Reproducer 1 from this PR's regression test (GLOBAL NOT IN concat(*, modulo(...)) against test_overlap) → completes cleanly, no crash.
  • Reproducer 2 (Decimal table with multi-arg multiIf over correlated subqueries) → same.

CIDB confirms: STID 2980-385f had 0 master hits and only 1 PR hit in the last 30 days.

This matches @alexey-milovidov's reasoning when closing the parallel #100617 today ("As we can't reproduce it - closing"). Some upstream change in the analyzer/planner between April and now appears to have removed the column-duplication code path that reached the assertion. This PR's Bugfix validation (functional tests) correspondingly fails because the regression test no longer fails on master HEAD.

The targeted AST fuzzer failure on this PR (STID 2651-2cfd "Trying to extract chunk from ChunkBuffer") is unrelated and separately tracked under #103322.

If anyone wants the two reproducers preserved as a non-crash regression defense, they can be lifted into a separate test without the assertion-side change — happy to follow up with that on request.

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