Skip to content

Fix logical error for Distributed table with empty remote database under distributed_product_mode=local - #110677

Merged
azat merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-astidentifier-empty-db-distributed-local
Aug 10, 2026
Merged

azat merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-astidentifier-empty-db-distributed-local

Conversation

@groeneai

@groeneai groeneai commented Jul 16, 2026 •

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

Fixed a logical error (!part.empty()) when a Distributed table defined with an empty remote database name is used in a JOIN with distributed_product_mode = 'local'.

Description

ASTTableIdentifier::resetTable, called when distributed_product_mode = 'local' rewrites a Distributed table to its remote table, built the identifier via the (String, String) constructor. An empty remote database is legal (it means the current database on the remote), but that constructor produced an empty leading name-part, tripping chassert(!part.empty()) in the ASTIdentifier constructor. It now builds from a StorageID, which already collapses an empty database to a single-part name.

Found by the AST fuzzer (STID 2508-3750). Reproducer:

CREATE TABLE dl (key String) ENGINE = Distributed('test_cluster_two_shards_different_databases', '', 'larger_table');
CREATE TABLE ds (key String) ENGINE = Distributed('test_cluster_two_shards_different_databases', '', 'smaller_table');
EXPLAIN AST optimize = 1 SELECT count() FROM dl AS lt INNER JOIN ds AS rt ON lt.key = rt.key
SETTINGS distributed_product_mode = 'local';

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110633&sha=ea2a114066175d6c883deeb89b0d32d84760e28c&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. EXPLAIN AST optimize=1 SELECT count() FROM <dist_empty_db> AS lt INNER JOIN <dist_empty_db> AS rt ON lt.key=rt.key SETTINGS distributed_product_mode='local' aborts every time on the buggy binary.
b Root cause explained? Distributed table with empty remote database + distributed_product_mode=local -> InJoinSubqueriesPreprocessor::renameIfNeeded -> ASTTableIdentifier::resetTable("", table) -> ASTTableIdentifier(String,String) builds {"", table} with an empty leading name-part -> chassert(!part.empty()) at ASTIdentifier.cpp:48 aborts in debug/sanitizer builds.
c Fix matches root cause? Yes. The (String,String) ctor now drops the empty database and builds a single-part identifier, exactly as the sibling ASTTableIdentifier(StorageID) ctor already does.
d Test intent preserved / new test added? New stateless test 04500_distributed_product_mode_local_empty_database reproduces the exact trigger via EXPLAIN AST and asserts the rewrite succeeds with no abort.
e Demonstrated in both directions? Yes. Baseline binary (Build ID 6060377f): SIGABRT Logical error: '!part.empty()', server dies. Fixed binary (Build ID 940917c7): clean deterministic AST output, server alive; reference matches 3/3 runs.
f Fix is general, not a narrow patch? The only other (database, table) -> identifier path (ASTTableIdentifier(StorageID)) already handled empty-db correctly; this ctor was the sole inconsistent one. The single-arg ctor takes only a table name.
g Generalizes across inputs? Verified non-empty-db (unchanged behavior) and empty-db (fixed) variants, analyzer on/off. Empty-db is the boundary input; non-empty passes through the two-part branch as before.
h Backward compatible? Yes. No setting/format/behavior change for valid queries; only removes a debug/sanitizer abort. Release builds already threw a handled exception.
i Invariants preserved? Yes. ASTIdentifier's "every name-part is non-empty" invariant is now upheld for this ctor; getTableId()/getDatabaseName() already handle the 1-part case (database = empty), matching the StorageID ctor.

Session id: cron:clickhouse-worker-slot-6:20260716-111500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @azat — could you review this? It fixes an ASTIdentifier !part.empty() abort: ASTTableIdentifier(database, table) built an identifier with an empty leading name-part when a Distributed table has an empty remote database and is rewritten under distributed_product_mode=local. The fix mirrors the existing ASTTableIdentifier(StorageID) constructor (single-part identifier when the database is empty).

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d9d7947]

Summary: ✅


AI Review

Summary

This PR narrows the old-analyzer !part.empty() abort in ASTTableIdentifier::resetTable by rebuilding the rewritten table name from StorageID, and the new 04500 test proves that the AST rewrite no longer asserts. I do not think it fully fixes the advertised empty-remote-database JOIN case, though: on the old-analyzer execution path, the rewritten right-hand table is still re-qualified with currentDatabase(), so clusters that rely on per-shard default_database continue to fail the query after this patch.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/110677#discussion_r3608912742] [src/Parsers/ASTIdentifier.cpp:474, src/Interpreters/ClusterProxy/SelectStreamFactory.cpp:99, src/Interpreters/AddDefaultDatabaseVisitor.h:261] resetTable now turns ("", table) into a short identifier, but the old-analyzer remote rewrite still runs AddDefaultDatabaseVisitor(..., only_replace_in_join = true) over JOIN operands. That visitor re-qualifies the rewritten right-hand table with context->getCurrentDatabase(), so a cluster that intentionally leaves remote_database empty to use each shard's default_database still executes ... JOIN current_db.table instead of preserving the per-shard lookup. The new 04500 EXPLAIN AST test never reaches remote dispatch, so the current head still does not make the advertised old-analyzer JOIN work; it only replaces the abort with UNKNOWN_TABLE or a wrong-target lookup.
    Suggested fix: either carry an explicit "empty remote database" marker through the old-analyzer rewrite so AddDefaultDatabaseVisitor skips that table, or add a focused old-analyzer execution test and narrow the PR/entry to "removes the logical error" if preserving shard defaults is intentionally out of scope.
Final Verdict

Changes requested. The assertion is gone, but the old-analyzer JOIN path still mishandles empty remote databases on clusters that rely on per-shard default_database.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.90% 78.90% +0.00%

Changed lines: Changed C/C++ lines covered: 2/2 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 16, 2026
…se and distributed_product_mode=local

Rewriting a Distributed table to its remote table under
distributed_product_mode=local builds an ASTTableIdentifier from the remote
(database, table) pair. When the remote database name is empty (a legal
Distributed definition meaning the current database on the remote), the
(String, String) constructor produced an identifier with an empty leading
name-part, which trips chassert(!part.empty()) in the ASTIdentifier
constructor and aborts the server in debug/sanitizer builds (a handled
exception in release). Found by the AST fuzzer (STID 2508-3750).

Mirror the existing ASTTableIdentifier(StorageID) constructor: when the
database is empty, build a single-part identifier. Only do this when there
are no name parameters: a parameterized identifier such as
{db:Identifier}.{tbl:Identifier} legitimately carries empty name-parts that
are filled by the corresponding name_params children, and collapsing them
would drop the placeholder and break identifier formatting/resolution.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-astidentifier-empty-db-distributed-local branch from 1685a48 to b599aa5 Compare July 16, 2026 16:57
@groeneai

Copy link
Copy Markdown
Collaborator Author

The previous revision collapsed {"", table} -> {table} unconditionally, which also dropped the empty leading name-part of parameterized identifiers like {db:Identifier}.{tbl:Identifier} (that empty part is a placeholder filled by the identifier's name_params child). That broke identifier formatting/resolution across the Fast test suite (100+ result-diffs).

Refined the guard to database_name.empty() && name_params.empty(): the single-part collapse now applies only to the empty-remote-database Distributed rewrite path (which has no name params), leaving parameterized identifiers byte-identical to before. The ASTIdentifier ctor already only asserts non-empty parts when name_params is empty, so this exactly matches where the assertion fires.

Verified locally (debug):

  • Original repro: no longer aborts, server stays alive.
  • 04500 regression test: 3/3 pass.
  • Previously-regressed Fast tests (02339_analyzer_matcher_basic, 02014_query_parameters, 01048_exists_query, 01470_show_databases_like): pass.
  • {db:Identifier}.{tbl:Identifier} returns correct results.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b599aa5

CI finished on the prior head. The earlier broad Fast test regression (empty-table/UNKNOWN_TABLE identifier resolution) was fixed on this head by the name_params.empty() guard (Fast test now green). One real failure remained, now owned; merged master to pick up its merged fix.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Received signal 8 SIGFPE in EnabledQuota::Interval::getEndOfInterval (STID 4141-584d) trunk quota zero-length-interval division-by-zero (25+ unrelated PRs + 5 master rows/30d; not related to this PR's ASTIdentifier parser diff) #110846 (merged 2026-07-18), merged master @ f7229f3 to pick it up
Finish Workflow / Post Hooks derivative (red only due to the Stress line above) resolved by the above

Session id: cron:our-pr-ci-monitor:20260718-173000

Comment thread src/Parsers/ASTIdentifier.cpp Outdated
ASTTableIdentifier::ASTTableIdentifier(const String & database_name, const String & table_name, ASTs && name_params)
: ASTIdentifier({database_name, table_name}, true, std::move(name_params))
: ASTIdentifier(
(database_name.empty() && name_params.empty())

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.

Collapsing ("", table) to a short identifier fixes the ASTIdentifier invariant, but on the old-analyzer JOIN path it also changes the remote-dispatch behavior. InJoinSubqueriesPreprocessor::resetTable now leaves the rewritten table non-compound, and ClusterProxy::rewriteSelectQuery still runs the JOIN-only AddDefaultDatabaseVisitor (SelectStreamFactory.cpp:95-102 / AddDefaultDatabaseVisitor.h:176-191), which re-qualifies it with context->getCurrentDatabase(). On clusters that intentionally use an empty remote database so each shard falls back to its own default_database (for example test_cluster_two_shards_different_databases), the shard query becomes current_db.table instead of preserving the per-shard default. The new EXPLAIN AST test won't see this because it never goes through remote dispatch. I think this still needs either a marker that suppresses that JOIN requalification for empty-remote-db rewrites, or an old-analyzer execution test modeled on 04303_58766_distributed_product_mode_local_default_database.sql.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Verified on a debug build (this branch) vs the same file reverted to master, same query and cluster config (test_cluster_two_shards_different_databases, per-shard default_database).

The mechanism is correct: the collapsed non-compound table gets re-qualified to current_db.table by AddDefaultDatabaseVisitor(only_replace_in_join). But that path did not preserve the per-shard default before the fix either. On master the identical old-analyzer JOIN aborts the server:

Logical error: '!part.empty()' at InJoinSubqueriesPreprocessor.cpp:96 -> resetTable -> ASTIdentifier ctor (signal 6)

Measured on this branch:

For a non-empty remote db the constructor is byte-identical to master (the else branch), so only the empty-remote-db case, which crashed, is affected. The remaining UNKNOWN_TABLE is a pre-existing limitation of the old-analyzer JOIN rewrite (the release-build symptom is the empty-backtick SYNTAX_ERROR documented in 04303); enable_analyzer=1 resolves it. A JOIN execution test can't assert a passing result since that path never worked. I can add a marker suppressing the JOIN re-qualification for empty-remote-db rewrites if that resolution is preferred; leaving the disposition to the assignee.

@clickhouse-gh

clickhouse-gh Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.10% 86.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.20% 78.20% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f7229f3 (clean)

CI fully finished on this head (a master merge that picked up the fix for the one real failure from the prior head). No failures remain.

Check / test Reason Owner / fixing PR
(none) — all green (159 pass / 18 skip / 0 fail)

Session id: cron:our-pr-ci-monitor:20260718-223000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f7229f3

Every check has an owner; only CH Inc sync is exempt. CI fully finished and clean on this head.

Check / test Reason Owner / fixing PR
(none) CI fully finished: 160 success, 18 skipped, 0 failures —

The earlier Fast-test regression (empty-table/UNKNOWN_TABLE) was on stale head 1685a48 and fixed by the name_params.empty() guard; the Stress test (amd_tsan) SIGFPE quota finding was owned by #110846 (merged), picked up by merging master into this branch. All checks green on f7229f3.

Session id: cron:our-pr-ci-monitor:20260719-003000

@azat azat 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 don't like this, better to use auto identifier = make_intrusive<ASTTableIdentifier>(StorageID{database_name, table_name}); instead of auto identifier = make_intrusive<ASTTableIdentifier>(database_name, table_name); in the ASTTableIdentifier::resetTable

And keep only essentials in commits description, PR description and code comments

…se and distributed_product_mode=local

Rewriting a Distributed table to its remote table under
distributed_product_mode=local calls ASTTableIdentifier::resetTable with the
remote (database, table) pair. An empty remote database is legal (it means the
current database on the remote), but the (String, String) constructor built an
identifier with an empty leading name-part, tripping chassert(!part.empty()) in
the ASTIdentifier constructor. Build the identifier from a StorageID instead,
which already collapses an empty database to a single-part name.

Found by the AST fuzzer (STID 2508-3750).

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Done in d9d7947.

resetTable now builds from StorageID{database_name, table_name}, and the (String, String) constructor is reverted to its original form (byte-identical to master). Also trimmed the commit message, PR description and dropped the comment block from the test.

Verified on a debug build: the repro no longer aborts, and with only the constructor reverted (i.e. without the resetTable change) it still aborts at ASTIdentifier.cpp:48 via resetTable -> ASTTableIdentifier(String, String), so the new call site is what fixes it. 04500 passes 50/50; the parameterized-identifier tests that the previous constructor change had broken (02014_query_parameters, 02339_analyzer_matcher_basic, 01048_exists_query) pass again.

One behaviour difference worth flagging: StorageID validates its arguments, so an empty table name would now throw UNKNOWN_TABLE instead of hitting the assertion. That path is unreachable from DDL anyway (Distributed(cluster, 'db', '') is already rejected at CREATE by the same check), so this only replaces an abort with a handled exception.

@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d9d79479e with master ccd0884b7 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 9e886a226; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.67 MiB 687.65 MiB -3.02 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d9d7947

CI fully finished on this head (the head that addresses @azat's change requests) and it is clean. Every failure line would have an owner; there are none.

Check / test Reason Owner / fixing PR
(none) 158 success, 17 skipped, 0 failures; CIDB reports 0 FAIL/ERROR rows for this commit -

Config Workflow and Finish Workflow both concluded success, so the job matrix really ran (not a dropped/void run).

Session id: cron:our-pr-ci-monitor:20260810-010000

@azat
azat added this pull request to the merge queue Aug 10, 2026
Merged via the queue into ClickHouse:master with commit d420285 Aug 10, 2026
181 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
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 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.

4 participants