Skip to content

Fix LOGICAL_ERROR "Column identifier is already registered" in UNION ALL - #100770

Merged
tiandiwonder merged 7 commits into
ClickHouse:masterfrom
tiandiwonder:fix-union-column-identifier-100678
May 27, 2026
Merged

tiandiwonder merged 7 commits into
ClickHouse:masterfrom
tiandiwonder:fix-union-column-identifier-100678

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

The AST fuzzer can produce ASTSelectWithUnionQuery nodes where two UNION
branches share the same physical ASTPtr. If such sharing reaches the
analyzer, the resulting QueryTree can also contain shared nodes. When the
planner then registers column identifiers in the shared GlobalPlannerContext
— specifically in the columns_names.empty() fallback of
prepareBuildQueryPlanForTableExpression that picks a dummy "smallest column"
to read — the second branch throws a LOGICAL_ERROR ("Column identifier is
already registered").

Fix: after each recursive fuzz() round on UNION children, deduplicate
sibling branch pointers — any branch that is the same pointer as a
previously seen sibling is replaced with a clone, normalizing the invalid
shared state before it reaches the analysis pipeline.

Fix #100678

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Low Risk
Low risk: change is isolated to QueryFuzzer and only normalizes invalid fuzzer-generated UNION AST sharing by cloning duplicate sibling pointers.

Overview
Prevents the AST fuzzer from emitting UNION queries where multiple branches share the same underlying AST node.

After fuzzing ASTSelectWithUnionQuery children, the code now detects duplicate sibling ASTPtrs and replaces repeats with clone()d nodes, avoiding downstream analyzer/planner failures like LOGICAL_ERROR ("Column identifier is already registered").

Reviewed by Cursor Bugbot for commit 7b1d893. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.6.1.174

@tiandiwonder
tiandiwonder requested a review from Copilot March 26, 2026 01:40
@clickhouse-gh

clickhouse-gh Bot commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7b1d893]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL IGNORED

AI Review

Summary

This PR hardens QueryFuzzer::fuzz for ASTSelectWithUnionQuery by normalizing duplicate sibling branch pointers in list_of_selects via clone after recursive fuzzing. That directly addresses the reported invalid shared-branch state that can later trigger LOGICAL_ERROR (Column identifier is already registered) during planning. I reviewed the current PR diff and prior discussion threads; no remaining correctness, safety, or performance issues were found in the changed code.

Final Verdict

Status: ✅ Approve

Copilot AI left a comment

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.

Pull request overview

Fixes a planner LOGICAL_ERROR (“Column identifier is already registered”) that can occur in UNION ALL planning when both branches register the same dummy column identifier in a shared GlobalPlannerContext.

Changes:

  • Add GlobalPlannerContext::getOrCreateColumnIdentifier() to make column-identifier registration idempotent for specific planner paths.
  • Switch the dummy “smallest column” registration in prepareBuildQueryPlanForTableExpression() to use the idempotent API.
  • Add a regression test covering the UNION ALL + count() planning path.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/queries/0_stateless/04056_union_column_identifier_duplicate.sql Adds a regression query to exercise the UNION ALL planning path that triggers dummy column registration.
tests/queries/0_stateless/04056_union_column_identifier_duplicate.reference Adds expected output for the new regression query.
src/Planner/PlannerJoinTree.cpp Uses the new idempotent column-identifier registration in the dummy-read-column fallback.
src/Planner/PlannerContext.h Introduces the new getOrCreateColumnIdentifier() API with rationale and usage guidance.
src/Planner/PlannerContext.cpp Implements getOrCreateColumnIdentifier() to return an existing identifier instead of throwing.

Comment thread src/Planner/PlannerContext.cpp Outdated
Comment on lines 55 to 56
auto [it, inserted] = column_identifiers.emplace(column_identifier);
return *it;

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

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

inserted is computed but unused, which can trigger compiler warnings (and potentially fail builds if warnings are treated as errors). Consider avoiding the unused binding (e.g., use .emplace(...).first directly, or explicitly mark/suppress the unused value via (void)inserted / [[maybe_unused]]).

Suggested change
auto [it, inserted] = column_identifiers.emplace(column_identifier);
return *it;
return *column_identifiers.emplace(column_identifier).first;

Copilot uses AI. Check for mistakes.
Comment thread src/Planner/PlannerContext.cpp Outdated
Comment on lines +47 to +53
std::string column_identifier;

const auto & source_alias = column_source_node->getAlias();
if (!source_alias.empty())
column_identifier = source_alias + "." + column.name;
else
column_identifier = column.name;

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

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

The identifier formatting logic is now embedded in getOrCreateColumnIdentifier(). To reduce the risk of future divergence from createColumnIdentifier() (e.g., if identifier formatting rules change), consider extracting this formatting into a single shared helper (private method/free function) used by both APIs.

Copilot uses AI. Check for mistakes.
@tiandiwonder
tiandiwonder force-pushed the fix-union-column-identifier-100678 branch from 99b7671 to d67458f Compare March 26, 2026 07:26
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, investigate and fix the failure of the integration test, "test_format_avro_confluent". Send a separate PR with the fix or link the existing PR here.

@groeneai

groeneai commented May 5, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — investigated; no fix is needed. Details:

What was the failure?

Commit cb6d0bd6, run on 2026-03-28 23:40:29 UTC, in Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6). The test was test_format_avro_confluent/test.py::test_select_auth, failing in fixture setup at line 111:

File: test_format_avro_confluent/test.py:111 - in test_select_auth
    message = serializer.encode_record_with_schema("test_subject_auth", schema, {"value": x})
File: confluent_kafka/avro/serializer/message_serializer.py:107 - in encode_record_with_schema
    schema_id = self.registry_client.register(subject, schema)
File: confluent_kafka/avro/cached_schema_registry_client.py:269 - in register
    raise ClientError(...)
E   confluent_kafka.avro.error.ClientError:
E       Unable to register schema. Error code:500 message:{'error_code': 50002, 'message': 'Register operation timed out'}

This is the schema-registry container itself returning HTTP 500 with Register operation timed out — a transient Docker/HTTP infrastructure issue inside the Confluent Schema Registry (schemaregistry) container, before any ClickHouse code is even involved.

It already self-resolved

All six Integration tests (amd_asan_ubsan, db disk, old analyzer, N/6) shards on commit cb6d0bd6 completed with success on 2026-03-29 00:25–00:55 UTC (post-rerun). Same for all amd_msan, amd_tsan, amd_binary, and arm_binary, distributed plan shards. CIDB confirms check_status = 'success' for all integration shards on this PR's latest commit.

Not caused by this PR

PR #100770's diff is a single hunk in src/Common/QueryFuzzer.cpp — clickhouse-client's SQL AST fuzzer. It only runs when --query-fuzzer-runs=N is passed, only operates on AST nodes for UNION ALL, and has no path to HTTP networking, the Confluent Schema Registry client, the Avro format reader, or the integration-test Docker fixtures. There is no plausible mechanism by which this change can affect a Python integration test that posts a schema to a schema-registry container over HTTP.

Test is not chronically flaky either

30-day CIDB query for test_format_avro_confluent%:

Day master release-branch PR #100770 other PRs distinct PRs
2026-04-24 0 0 0 4 1 (PR #103519, batch failure across many integration tests on a single shard run)
2026-04-19 0 0 0 1 1 (PR #102405, single hit)

Master failures since 2026-01-01: only 4 hits, all on 2026-03-17 — which was a system-wide CI outage (130,519 integration-test failures across 4,812 distinct tests that day, not test-specific). Excluding that outage day, this test has had zero master failures in 2026.

Conclusion

  • Cause: transient schema-registry HTTP-500 timeout (infrastructure, not ClickHouse, not this PR).
  • Status: already self-resolved by rerun; latest CI for this PR shows all integration shards green.
  • Action: no fix PR needed. The test does not need a stability change either — it's not chronically flaky on master.

If a confluent_kafka.avro.error.ClientError: ... Register operation timed out reappears repeatedly we should harden the schema-registry waiter in tests/integration/helpers/cluster.py (similar to how MongoDB / Kafka waits work), but right now the rate doesn't justify it. I'll keep this on my radar via CIDB and open a fix if the pattern returns.

— Groene AI 🤖 (session cron:clickhouse-ci-task-worker:20260505-094500)

@novikd novikd self-assigned this May 5, 2026

@novikd novikd 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.

LGTM

@alexey-milovidov

Copy link
Copy Markdown
Member

Refreshed master to absorb 53 days of fixes. Workflow file was kept at the pre-merge state to bypass the OAuth workflow scope on the fork-push path.

@groeneai, please investigate the failure of 03599_lightweight_delete_vertical_merge in Stateless tests (amd_msan, WasmEdge, parallel, 2/2) (report) and provide a fix in a separate PR (or link the existing one). The failure is a timeout under randomized MergeTree settings — the change in this PR only touches QueryFuzzer.cpp and is unrelated. Test-history shows the same test timing out on PRs #96130, #103234, #101680, #93882, #99513, #100509, #100288 across multiple unrelated builds (Fast test, ASan, TSan, debug, WasmEdge, ParallelReplicas, …).

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov investigated 03599_lightweight_delete_vertical_merge per your directive. Filed fix PR #105427 (no-random-merge-tree-settings tag).

Cross-PR / 90-day CIDB confirms this is a chronic flake (not specific to PR #100770), matching what you described:

PR check_name reason
100770 amd_msan, WasmEdge Timeout (600.16 s) — ddmin: "MergeTree settings alone reproduce the failure"
99735 amd_msan, WasmEdge Timeout
93882 arm_asan_ubsan, azure Timeout 300 s waiting for DROP TABLE
101680 amd_tsan, flaky check "Test runs too long (>180 s)"
100509 Fast test Timeout
99513 ParallelReplicas, s3, llvm_coverage MEMORY_LIMIT_EXCEEDED (same family — pathological mark count under tiny granularity)
96130 / 99181 / 100288 / 103234 / 98358 various unrelated PR-caused errors, not in this category

Root cause: clickhouse-test injects MergeTree settings via --allow_merge_tree_settings. Settings the test does NOT pin in CREATE TABLE (most importantly index_granularity = 3 → ~33K marks for a 100K-row part) inflate the two OPTIMIZE TABLE FINAL vertical merges. Under ~25x MSan+WasmEdge slowdown, both merges combined exceed the 600 s per-test cap. --diagnose-random-settings ddmin bailed at its 300 s budget — consistent with a multiplicative slowdown across many settings rather than one isolatable culprit.

Fix: add -- Tags: no-random-merge-tree-settings. Sibling vertical-merge tests 02981_vertical_merges_memory_usage, 04041_vertical_merge_stop_start_race, 04145_vertical_merge_wide_rows_small_block_size already use the same tag, and 03599's CREATE TABLE SETTINGS already pins everything the test verifies (vertical_merge_algorithm_min_rows_to_activate = 1, vertical_merge_optimize_lightweight_delete = 1, min_bytes_for_wide_part = 0, ...), so removing the rest of the randomization changes runtime not coverage.

Local verification: 30/30 passes on debug with randomized regular settings still enabled.

This PR (100770) itself only touches QueryFuzzer.cpp and is unrelated to the failure — proceeding with the fix in #105427 unblocks the merge once it lands. Apologies for the slow turnaround.

Workflow files in this branch were stale or had been deleted as a
workaround for GitHub's workflow-scope check. Restoring them to match
`master` so the PR diff no longer contains those unrelated changes.
@clickhouse-gh

clickhouse-gh Bot commented May 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 83.33% (5/6) | lost baseline coverage: 51 line(s) · Uncovered code

Full report · Diff report

@tiandiwonder
tiandiwonder enabled auto-merge May 27, 2026 00:37
@tiandiwonder
tiandiwonder added this pull request to the merge queue May 27, 2026
Merged via the queue into ClickHouse:master with commit 835ad2e May 27, 2026
165 of 167 checks passed
@tiandiwonder
tiandiwonder deleted the fix-union-column-identifier-100678 branch May 27, 2026 00:56
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 27, 2026
github-merge-queue Bot pushed a commit that referenced this pull request Jul 9, 2026
…UPDATE with EXISTS

When the mutations analyzer rewrites `exists((subq))` to
`1 IN (SELECT 1 FROM (subq) LIMIT 1)` (the `only_analyze` path), the
resulting subquery tree can reach `buildSubqueryPlansForSetsAndAdd`
with inner source nodes that have no `__tableN` aliases. The planner
then registers `dummy` (or any bare column name) once via
`prepareBuildQueryPlanForTableExpression` for the wrapping `QueryNode`
and again via `CollectSourceColumnsVisitor` for the inner `TableNode`,
producing the LOGICAL_ERROR.

Re-running `createUniqueAliasesIfNecessary` on the detached subquery
tree before planning guarantees every table expression has a unique
alias, so the two registrations produce distinct identifiers like
`__table1.dummy` and `__table2.dummy`.

Adds a regression test that reproduces the original AST-fuzzer query
(STID 4697-4326) from issue #104877. The prior fix family
(#100770, #101048, #101051, #101104) addressed the same error class
for UNION ALL / additional_result_filter SELECT paths but did not
cover the mutations + EXISTS pattern.

Issue: #104877
STID: 4697-4326
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=3120048c80b01b65ef75858d34e17b669505de6a&name_0=MasterCI&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
…r runners

Add `no-random-merge-tree-settings` so the CI runner does not inject
defaults like `index_granularity = 3` that turn the two `OPTIMIZE FINAL`
vertical merges into a >600 s walk under MSan + WasmEdge and similar slow
runners. The test already pins every MergeTree setting it cares about
(`min_bytes_for_wide_part = 0`, `vertical_merge_algorithm_min_rows_to_activate = 1`,
`vertical_merge_optimize_lightweight_delete = 1`, ...) in the table SETTINGS,
so randomizing the rest only adds variance, not coverage.

Sibling vertical-merge tests 02981, 04041, 04145 use the same tag.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100770&sha=fe0c8cb7986e4c9b83529a24215c5ed28b2a2137&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20WasmEdge%2C%20parallel%2C%202%2F2%29
PR: ClickHouse#100770
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…UPDATE with EXISTS

When the mutations analyzer rewrites `exists((subq))` to
`1 IN (SELECT 1 FROM (subq) LIMIT 1)` (the `only_analyze` path), the
resulting subquery tree can reach `buildSubqueryPlansForSetsAndAdd`
with inner source nodes that have no `__tableN` aliases. The planner
then registers `dummy` (or any bare column name) once via
`prepareBuildQueryPlanForTableExpression` for the wrapping `QueryNode`
and again via `CollectSourceColumnsVisitor` for the inner `TableNode`,
producing the LOGICAL_ERROR.

Re-running `createUniqueAliasesIfNecessary` on the detached subquery
tree before planning guarantees every table expression has a unique
alias, so the two registrations produce distinct identifiers like
`__table1.dummy` and `__table2.dummy`.

Adds a regression test that reproduces the original AST-fuzzer query
(STID 4697-4326) from issue ClickHouse#104877. The prior fix family
(ClickHouse#100770, ClickHouse#101048, ClickHouse#101051, ClickHouse#101104) addressed the same error class
for UNION ALL / additional_result_filter SELECT paths but did not
cover the mutations + EXISTS pattern.

Issue: ClickHouse#104877
STID: 4697-4326
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=3120048c80b01b65ef75858d34e17b669505de6a&name_0=MasterCI&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-ci 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.

Logical error: Column identifier A is already registered (STID: 4697-369d)

6 participants