Skip to content

Fix LOGICAL_ERROR "Column identifier is already registered" in ALTER UPDATE with EXISTS - #106025

Merged
alexey-milovidov merged 15 commits into
ClickHouse:masterfrom
groeneai:fix-stid-4697-4326-mutations-column-identifier
Jul 9, 2026
Merged

alexey-milovidov merged 15 commits into
ClickHouse:masterfrom
groeneai:fix-stid-4697-4326-mutations-column-identifier

Conversation

@groeneai

@groeneai groeneai commented May 28, 2026 •

Copy link
Copy Markdown
Collaborator

Adds a regression test for the chronic AST-fuzzer LOGICAL_ERROR "Column identifier ... is already registered" (STID 4697-4326) on the mutations + EXISTS path, and for the rejection of correlated subqueries in mutations.

The two code fixes this test guards have since landed on master independently, so this PR is now test-only (per @novikd's review: "remove the code added in #106414, keep the test"; correlated subqueries should not be allowed in mutations):

  1. Non-correlated EXISTS over a real source table no longer aborts the server. The createUniqueAliasesIfNecessary call on each detached subquery in MutationsInterpreter (added by Fix logical error "Column identifier ... is already registered" in mutations #106414) gives the inner source nodes unique __tableN aliases, so buildColumnIdentifier no longer registers the same bare column name twice.
  2. Correlated subqueries inside ALTER UPDATE / ALTER DELETE are rejected with a clean NOT_IMPLEMENTED by correlated_subtrees.assertEmpty("in mutation filter"/"in mutation update") in MutationsInterpreter::prepareMutationStages.

The earlier ValidateNoCorrelatedSubqueryVisitor gate that this PR carried added no behavior over master (every case in the test is already handled by the two pieces above — Bugfix validation confirms the test passes on the unfixed base), so it was removed and MutationsInterpreter.cpp is restored to master.

The test 04303_stid_4697_4326_mutation_exists_column_identifier covers:

It is tagged no-old-analyzer: the bug class lives in the new analyzer's EXISTS rewrite; the old analyzer rejects these shapes with a different error before the planner runs.

Closes: #106649
Related: #106414

CI 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

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

Add a regression test for LOGICAL_ERROR "Column identifier is already registered" on the ALTER UPDATE/ALTER DELETE + EXISTS path and for NOT_IMPLEMENTED rejection of correlated subqueries in mutations. The fixes themselves are already on master.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.732 (included in 26.7 and later)
  • Backported to: 26.6.2.58

…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
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @novikd — could you review this? Fix for chronic AST-fuzzer error "Column identifier is already registered" (STID 4697-4326, issue #104877) on the mutations + EXISTS path. The analyzer rewrites exists((subq)) to 1 IN (SELECT 1 FROM (subq) LIMIT 1) in only_analyze mode, and the subquery tree reaches buildSubqueryPlansForSetsAndAdd with inner source nodes that lack __tableN aliases — causing both prepareBuildQueryPlanForTableExpression and CollectSourceColumnsVisitor to register the same bare column name. The fix re-runs createUniqueAliasesIfNecessary on the detached subquery tree before planning. The prior fix family (#100770, #101048, #101051, #101104) addressed the same error class on the SELECT side but did not cover this mutations path.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (session cron:clickhouse-ci-task-worker:20260528-031500):

a) Deterministic repro? Yes. Minimal command (debug build): ALTER TABLE t UPDATE v = 0 WHERE exists((SELECT * FROM system.one)) SETTINGS mutations_sync = 2 aborts the server on every run with LOGICAL_ERROR: Column identifier dummy is already registered. The original AST-fuzzer query from CIDB (ALTER TABLE test_updates (UPDATE dynamic = NULL WHERE exists((SELECT DISTINCT *, currentDatabase() > database)))) reproduces with the same stack.

b) Root cause explained? Yes. In only_analyze mode (mutations dry_run during validate()), QueryAnalyzer::resolve rewrites exists((subq)) -> 1 IN (SELECT 1 FROM (subq) LIMIT 1). collectSets stores that IN subquery in PreparedSets. buildSubqueryPlansForSetsAndAdd later detaches the subquery and creates a fresh GlobalPlannerContext per subquery. The detached tree's inner source nodes (the wrapping QueryNode and inner TableNode) lack the __tableN aliases that createUniqueAliasesIfNecessary would normally provide. buildColumnIdentifier thus produces a bare dummy for both the wrapping QueryNode (via prepareBuildQueryPlanForTableExpression -> createColumnIdentifierOrGet) and the inner TableNode (via CollectSourceColumnsVisitor::enterImpl -> createColumnIdentifier), and the second call hits the duplicate-insert throw.

c) Fix matches root cause? Yes. Re-running createUniqueAliasesIfNecessary(query_tree, context_) on the detached subquery before constructing the per-subquery Planner is the direct upstream of the missing-alias state: it assigns unique __tableN aliases to every TableNode / TableFunctionNode / nested QueryNode / UnionNode in the subquery, so the two registration sites produce distinct identifiers like __table1.dummy and __table2.dummy. Not a defensive widen of the assertion, not a no-random-* tag.

d) Test intent preserved? / New test added? Yes. New regression test 04300_stid_4697_4326_mutation_exists_column_identifier covers the minimal trigger, the original AST-fuzzer query, and a NOT EXISTS variant. Existing tests for the related error class (04064_planner_duplicate_column_identifier, 04064_additional_result_filter_union_column_identifier, 04066_union_all_column_identifier_collision) still pass without modification.

e) Demonstrated in both directions? Yes.

  • Without fix (stashed): clickhouse-test 04300_stid_4697_4326 fails with Having 1 errors! (server crashes on the first mutation).
  • With fix: 20/20 passes in --test-runs 20. Related fix-family tests: 15/15 passes over --test-runs 5 for the three regression tests above.

f) Fix is general, not a narrow patch? Yes. The fix targets buildSubqueryPlansForSetsAndAdd -- the single place where mutations re-plan subqueries with their own per-subquery GlobalPlannerContext. Other related code paths handle this correctly:

  • Planner.cpp's addBuildSubqueriesForSetsStepIfNeeded (line ~1591) uses the regular SELECT path where createUniqueAliasesIfNecessary is already called upstream by InterpreterSelectQueryAnalyzer.
  • addBuildSubqueriesForMaterializedCTEsIfNeeded plans CTE bodies that were already aliased before being attached to a TableNode.

Walked the callers of createColumnIdentifier / createColumnIdentifierOrGet (CollectTableExpressionData.cpp:109, CollectTableExpressionData.cpp:158, PlannerJoinTree.cpp:494) -- they all rely on the source node already having a unique alias. The fix re-establishes that invariant before the planner runs.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0c72215]

Summary: ✅


AI Review

Summary

This PR is now a test-only change: it adds 04303_stid_4697_4326_mutation_exists_column_identifier to cover the mutation EXISTS / NOT EXISTS regression shapes, correlated-subquery rejection in mutations, and the #106649 derived-table IN reproducer. I did not find any unresolved correctness, coverage, or PR-metadata problems in the current diff, and the earlier bot threads about the wrong issue reference / Closes target are fixed in the current PR state.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 28, 2026
The fix re-runs `createUniqueAliasesIfNecessary` on detached subquery
trees inside the new analyzer's `Planner` path. The old analyzer takes
a different code path (`TreeRewriter::collectUsedColumns`) and rejects
the AST-fuzzer query shape (`SELECT DISTINCT *, currentDatabase() >
database`) with `UNKNOWN_IDENTIFIER` before any planner step runs, so
the bug cannot manifest there and the test cannot meaningfully run on
the old analyzer.

CI failure on the old-analyzer variant:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106025&sha=0d93b2f6bd9ece61ca2aef4f2c2a153f41860377&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DatabaseReplicated%2C%20WasmEdge%2C%20parallel%29

Also rewords the test header's `LOGICAL_ERROR` reference to "the
exception", per the project rule that logical errors do not crash the
server in release builds.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 3f0bc59d4d3d adding -- Tags: no-old-analyzer to 04300_stid_4697_4326_mutation_exists_column_identifier.sql.

Why this is correct, not a band-aid:

  • The fix is in the new analyzer's Planner path (createUniqueAliasesIfNecessary re-run on each detached subquery tree from PreparedSets).
  • The old analyzer never reaches GlobalPlannerContext::registerIdentifier for this query. Its TreeRewriter::collectUsedColumns rejects the AST-fuzzer query shape (SELECT DISTINCT *, currentDatabase() > database) with UNKNOWN_IDENTIFIER before any planner step runs, because the bare database column does not resolve in the old analyzer's EXISTS rewrite.
  • So the bug class verified by this test cannot manifest on the old analyzer; running it there produces a different, unrelated error.

CI failure that motivated this:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106025&sha=0d93b2f6bd9ece61ca2aef4f2c2a153f41860377&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DatabaseReplicated%2C%20WasmEdge%2C%20parallel%29

For reference, the other three failing checks on the current commit are not caused by this PR:

  1. AST fuzzer (amd_debug) STID 0250-20a8 ("Column query tree node does not have valid source node after running C pass"): chronic trunk bug, multiple PRs in the last 7 days.
  2. BuzzHouse (amd_msan) STID 2518-4199 (MSan use-of-uninitialized-value in UserDefinedSQLFunctionVisitor): chronic trunk MSan bug, tracked separately under issue MemorySanitizer: use-of-uninitialized-value (STID: 2518-3457) #106040.
  3. Bugfix validation: framework quirk where the inverter expects FAIL on master + PASS on PR, but the master-side ALTER UPDATE server-aborts (not a clean SQL error).

Pre-PR validation gate for this follow-up commit:

(a) Deterministic repro of the original failure: confirmed by the CI log linked above; query 9 (ALTER TABLE test_updates_04300 (UPDATE dynamic = NULL WHERE exists((SELECT DISTINCT *, currentDatabase() > database))) SETTINGS mutations_sync = 2) fails with Code: 47. ... UNKNOWN_IDENTIFIER on the old-analyzer variant.
(b) Root cause explained: see above. New-analyzer code path / old-analyzer code path divergence at EXISTS rewrite time.
(c) Fix matches root cause: no-old-analyzer is the standard mechanism in tests/clickhouse-test for this exact case ("test exercises new-analyzer-only behavior"). Sibling tests in the same fix family use enable_analyzer = 1 query-level, but those tests are single-query; this test has multiple ALTER ... mutations_sync = 2 queries and is more cleanly skipped wholesale.
(d) Test intent preserved: the test still exercises the same three patterns (minimal EXISTS, AST-fuzzer shape, NOT EXISTS) against the new analyzer where the bug actually lived.
(e) Both directions demonstrated: the pre-fix master HEAD (commit f8f58430da41) reproduces the original Logical error: Column identifier dummy is already registered exception when running this test, exactly the bug class the test guards. With the fix on this PR, the new-analyzer Stateless tests variant passes (162-job report column, only the old-analyzer variant fails). The change here removes the spurious old-analyzer failure, nothing else.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, why does the bugfix validation check fail to reproduce it?

@alexey-milovidov alexey-milovidov self-assigned this May 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov The test does reproduce the bug on master HEAD. The artifact core.TCPHandler.1608-4962.zst.enc on this run is the server core dump from the LOGICAL_ERROR: 'Column identifier dummy is already registered' that abort_on_logical_error=true (CI default in tests/config/config.d/abort_on_logical_error.yaml) converts to SIGABRT via abortOnFailedAssertion in src/Common/Exception.cpp. After the server dies, tests/clickhouse-test's check_server_liveness raises StopTesting, the worker-to-parent SIGTERM feedback loop in stop_tests kicks the parent out, and the bash pipeline exits with 143 (128 + SIGTERM).

The reason that did not surface as "bug reproduced" is a 30-hour timing gap. PR #105643 widened FTResultsProcessor's aborted-run synthesis from runner_exit_code == STOP_TESTING_EXIT_CODE (only 2) to runner_exit_code in {2, 137, 143, -15, -9} and adds a synthetic Server died FAIL leaf that the bugfix-validation inverter would then flip to OK. That merged into master on 2026-05-29 18:14 UTC (commit db6d7a5e). #106025's Bugfix validation ran on 2026-05-28 12:30 UTC, 30 hours earlier, so at that SHA the runner exit 143 did not match the single-value check. The run took the elif not s.success_finish branch and produced Tests = ERROR / "The test runner was terminated unexpectedly", and my #105789 inverter preserved that ERROR instead of overwriting it with the misleading "Failed to reproduce the bug".

I will merge master in to pick up #105643 and trigger a fresh run; with the wider ABORTED_RUN_EXIT_CODES, the bugfix-validation result should flip to OK / "bug reproduced".

@groeneai groeneai mentioned this pull request May 31, 2026
1 task
@novikd

novikd commented Jun 3, 2026

Copy link
Copy Markdown
Member

Should we allow correlated subqueries in mutations at all?

@novikd novikd self-assigned this Jun 3, 2026

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

Temporarily block.

@groeneai

groeneai commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator Author

@novikd Good question, and I want to be precise about what this PR does and does not do.

This PR does not add support for correlated subqueries in mutations. It fixes a server crash (LOGICAL_ERROR: 'Column identifier ... is already registered', which becomes a SIGABRT under abort_on_logical_error) on ALTER ... UPDATE/DELETE ... WHERE EXISTS((subquery)) shapes that the parser and analyzer already accept today. The regression test cases are predominantly uncorrelated, e.g.:

ALTER TABLE t UPDATE v = 0 WHERE exists((SELECT * FROM system.one)) SETTINGS mutations_sync = 2;
ALTER TABLE t UPDATE v = 1 WHERE NOT exists((SELECT * FROM system.numbers WHERE number > 1000000 LIMIT 1)) SETTINGS mutations_sync = 2;

The analyzer rewrites exists((subq)) into 1 IN (SELECT 1 FROM (subq) LIMIT 1) in only-analyze mode. The detached subquery source nodes have no __tableN alias, so two registration sites compute the same bare column identifier and the duplicate insert throws. The fix re-runs createUniqueAliasesIfNecessary on the detached subquery before building its per-subquery Planner, so the identifiers are unique again. No mutation semantics change.

If the team's preference is that such subqueries (correlated or not) should not be allowed in mutations at all, that is a separate decision. I am happy to instead implement a clean analyzer-level rejection that produces a proper user error rather than a crash. Either direction removes the abort. I just want to confirm which one you want before I touch it.

@KochetovNicolai Understood on the temporary block. Could you confirm what unblocks this: fix the crash as written here, or reject these queries with a clean error in the analyzer? I will follow whichever you and @novikd prefer.

@KochetovNicolai

Copy link
Copy Markdown
Member

@groeneai, please deprecate correlated subqueries in mutations.
non-correlated exists should work. Technically, we can allow correlated subqueries within scalar subqueries or IN (if it simplifies the code).

Per @KochetovNicolai and @novikd review on PR ClickHouse#106025:
correlated subqueries in `ALTER UPDATE` / `ALTER DELETE` are
deprecated. Non-correlated `EXISTS` continues to work via the
existing `createUniqueAliasesIfNecessary` fix in
`buildSubqueryPlansForSetsAndAdd`.

A new in-depth visitor walks the resolved mutation expression
right after `QueryAnalyzer::resolve` and throws `NOT_IMPLEMENTED`
on any `QueryNode` / `UnionNode` that has correlated columns.
This produces a clean user error instead of letting the query
reach the planner where it would previously raise the
`Logical error: 'Column identifier ... is already registered'`
exception (and abort the server in debug / sanitizer builds).

Test extends `04303_stid_4697_4326_mutation_exists_column_identifier`
with three correlated cases that must error with `NOT_IMPLEMENTED`:
correlated `EXISTS` over `system.one`-style subquery, correlated
`EXISTS` over `numbers(10)`, and correlated `EXISTS` inside
`ALTER DELETE`. Existing non-correlated `EXISTS` and `NOT EXISTS`
cases are kept and continue to pass.

PR-relatedness: pivot of PR ClickHouse#106025 in response to the team's
preferred direction (deprecate vs. fix-the-crash). The IN-function
gate at `src/Analyzer/Resolve/resolveFunction.cpp:1139` already
covers correlated `IN` arguments globally; this change adds the
parallel mutation-scope gate for `EXISTS` and any other correlated
subquery shape that survives analyzer rewrites.
@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

@KochetovNicolai @novikd Pivoted in 6a7a646.

Behavior:

  • Non-correlated EXISTS in mutations: works (the existing createUniqueAliasesIfNecessary call in buildSubqueryPlansForSetsAndAdd is kept; without it the bare-dummy collision still aborts the server on the canonical reproducer).
  • Correlated subqueries in mutations: rejected at analyzer time with NOT_IMPLEMENTED: Correlated subqueries are not supported in mutations: .... The gate is an in-depth visitor over the resolved mutation expression that flags any QueryNode / UnionNode with correlated columns. It mirrors the existing IN-argument gate at src/Analyzer/Resolve/resolveFunction.cpp:1139 but in MutationsInterpreter, so it covers EXISTS and any other correlated shape that survives analyzer rewrites.

Test 04303_stid_4697_4326_mutation_exists_column_identifier extends with three new cases that must error with NOT_IMPLEMENTED:

  • ALTER ... UPDATE WHERE exists((SELECT 1 WHERE id > 0))
  • ALTER ... UPDATE WHERE exists((SELECT * FROM numbers(10) WHERE number = id))
  • ALTER ... DELETE WHERE exists((SELECT 1 WHERE v < 100))

Existing non-correlated EXISTS and NOT EXISTS cases keep passing.

Re the carve-out you mentioned ("Technically, we can allow correlated subqueries within scalar subqueries or IN if it simplifies the code"): the current gate is strict - it rejects correlated wherever it appears. Correlated IN is already rejected globally (with a different message) by resolveFunction.cpp:1139. If you want me to relax this so correlated subqueries are allowed only when they appear as the right-hand argument of IN or as a scalar subquery, I can do that as a follow-up - it would need to teach the visitor to skip into those specific parents. Let me know which you prefer.

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Without the crash-fix half (kept here): ALTER TABLE t UPDATE v = 0 WHERE exists((SELECT * FROM system.one)) SETTINGS mutations_sync = 2 aborts the server (LOGICAL_ERROR on dummy column identifier collision in GlobalPlannerContext::createColumnIdentifier). For the new gate: ALTER TABLE t UPDATE v = 99 WHERE exists((SELECT 1 WHERE id > 0)) deterministically returns Code: 48 NOT_IMPLEMENTED: Correlated subqueries are not supported in mutations: ....
b Root cause explained? Yes (two halves). (1) Non-correlated exists((subq)) is rewritten to 1 IN (SELECT 1 FROM (subq) LIMIT 1); the detached subquery reaches buildSubqueryPlansForSetsAndAdd with inner source nodes that have no __tableN aliases, so two registration sites compute the same bare column identifier for dummy and the duplicate-insert throws. The fix re-runs createUniqueAliasesIfNecessary per detached subquery before planning. (2) Correlated subqueries in mutations were the team-decided "don't support" surface (KochetovNicolai 2026-06-04T13:10:02Z); the new gate runs after QueryAnalyzer::resolve and rejects them at analyzer time before the planner can hit any LOGICAL_ERROR path.
c Fix matches root cause? Yes. Half (1) puts unique aliases on the source nodes that the planner then registers, so the duplicate identifier disappears at the source. Half (2) is a clean analyzer-time rejection at the precise scope (mutation expression list) where the team wants it; mirrors the existing IN-argument correlated-rejection gate at resolveFunction.cpp:1139. Neither half is a defensive guard near the throw site.
d Test intent preserved / new tests added? New regression test 04303_stid_4697_4326_mutation_exists_column_identifier covers both halves: 3 non-correlated cases (must pass: minimal real-table EXISTS, AST-fuzzer-derived shape, NOT EXISTS) and 3 correlated cases (must error with NOT_IMPLEMENTED: UPDATE with id > 0, UPDATE with number = id, DELETE with v < 100). Existing 03925_exists_with_mutations_execute_on_initator continues to pass (verified locally).
e Both directions demonstrated? Yes. Local ASan build, single-binary run on port 29200. Without the fix branch: server SIGABRTs on the minimal non-correlated repro. With the fix branch: non-correlated cases return rows as expected, correlated cases return Code: 48 NOT_IMPLEMENTED with no server abort. Output matches .reference exactly (zero-byte diff under --multiquery).
f Fix is general, not a narrow patch? Yes. Half (1) is a single per-subquery createUniqueAliasesIfNecessary invocation that handles every detached subquery in PreparedSets, so it covers any exists / IN-style rewrite that lands in the mutation planner path with a missing-alias source. Half (2) walks the entire mutation expression (filters AND update assignments) via InDepthQueryTreeVisitor, so any correlated QueryNode / UnionNode is caught regardless of which operator (EXISTS, scalar subquery, etc.) hosts it. Sibling correlated-subquery gates in IN argument resolution (resolveFunction.cpp:1139) and in JOIN resolution (QueryAnalyzer.cpp:4852-4857) are already in place; this adds the parallel mutation-scope gate.

Session id: cron:clickhouse-ci-task-worker:20260604-135400

@groeneai

Copy link
Copy Markdown
Collaborator Author

@novikd I built and tested both halves of this before touching the branch, and the result changes the picture:

1. #106414 is a non-correlated crash fix, not correlated-subquery support. Its only code change is one createUniqueAliasesIfNecessary(query_tree, ...) call in buildSubqueryPlansForSetsAndAdd (MutationsInterpreter.cpp:2030). I removed exactly that line on the current branch, rebuilt, and the server aborts:

DELETE FROM test_filter WHERE exists((SELECT DISTINCT * LIMIT 452));
-> Logical error: 'Column identifier dummy is already registered'  (SIGABRT)
   GlobalPlannerContext::createColumnIdentifier
   <- collectTableExpressionData <- Planner <- buildSubqueryPlansForSetsAndAdd

That query is not correlated (the inner SELECT just reads system.one); it is one of the cases in 04305_mutation_in_subquery_column_identifier, the test you asked to keep. So reverting #106414 re-breaks a kept test rather than removing correlated support.

2. Correlated subqueries in mutations are already rejected on master, independent of #106414. correlated_subtrees.assertEmpty(...) at MutationsInterpreter.cpp:1736 (filter) and :1798 (update) throws NOT_IMPLEMENTED: Correlated subqueries ... are not supported. I disabled my own gate, rebuilt, and every correlated case in 04303 still gets a clean Code: 48, no crash. So "correlated subqueries should not be allowed in mutations" already holds.

3. Consequence: my analyzer-scope gate (the visitor at :184) is redundant with that assertEmpty. The only non-redundant part of this PR vs master is the 04303 regression test.

Given that, the revert as written is not what we want. The coherent options:

  • (a) Drop my redundant gate, keep Fix logical error "Column identifier ... is already registered" in mutations #106414's crash fix (already on master) and the 04303 test. This is effectively a test-only PR with the CI Fix or Improvement category.
  • (b) If you specifically want correlated subqueries rejected earlier than today's assertEmpty (e.g. before the planner, with a mutation-specific message), I keep a gate but reuse traverseQueryTree per your other comment instead of a new visitor.

Reverting #106414's createUniqueAliasesIfNecessary is not on the table either way, since it guards the non-correlated crash. Which of (a)/(b) do you prefer? You also asked @ alexey-milovidov about touching #106414, so I will hold until you both agree.

alexey-milovidov and others added 2 commits June 30, 2026 05:40
…ions

Per @novikd's review (ClickHouse#106025
"remove the code added in ClickHouse#106414 (keep the test)") and the unresolved
thread asking to reuse `traverseQueryTree` instead of a new visitor.

Both halves of this PR's earlier code are now redundant with `master`:

* The non-correlated `EXISTS` crash-fix (`createUniqueAliasesIfNecessary`
  on the detached subquery) landed independently on `master` via ClickHouse#106414
  (`MutationsInterpreter.cpp`).
* Correlated subqueries in mutations are already rejected with
  `NOT_IMPLEMENTED` on `master` by `correlated_subtrees.assertEmpty("in
  mutation filter"/"in mutation update")` in
  `MutationsInterpreter::prepareMutationStages`.

This PR's `ValidateNoCorrelatedSubqueryVisitor` therefore added no
behavior over `master`; `Bugfix validation` confirms the regression test
`04303_stid_4697_4326_mutation_exists_column_identifier` already passes on
the unfixed base, so every case it covers is handled by the existing
`master` code. Restore `MutationsInterpreter.cpp` to `master` and keep only
the regression test.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-ci and removed pr-bugfix Pull request with bugfix, not backported by default labels Jun 30, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Reduced this PR to test-only and merged fresh master. New HEAD a22dc549f0a.

What changed

  • Removed the ValidateNoCorrelatedSubqueryVisitor gate; src/Interpreters/MutationsInterpreter.cpp is now byte-identical to master. This addresses @novikd's review ("remove the code … keep the test") and the traverseQueryTree thread (now moot — there is no visitor left). Net diff vs master is just the 04303 regression test.
  • The gate was redundant. Both behaviors it guarded are already on master:
  • Changelog category switched from Bug Fix to CI Fix or Improvement (the fixes are already on master; this PR only adds coverage).

Verification (master-behavior binary, clickhouse local):

case result
UPDATE … WHERE exists((SELECT * FROM system.one)) 1 0 / 2 0, no crash
UPDATE dynamic = NULL WHERE exists((SELECT DISTINCT *, currentDatabase() > database)) 1 1 / 2 1
UPDATE … WHERE NOT exists((SELECT … system.numbers … LIMIT 1)) 1 10 / 2 20 (filter false)
UPDATE … WHERE exists((SELECT 1 WHERE id > 0)) (correlated) Code: 48 NOT_IMPLEMENTED
UPDATE … WHERE exists((SELECT * FROM numbers(10) WHERE number = id)) (correlated) Code: 48 NOT_IMPLEMENTED
DELETE WHERE exists((SELECT 1 WHERE v < 100)) (correlated) Code: 48 NOT_IMPLEMENTED
#106649 id IN (… JOIN …) shape count() = 0, no crash

Output matches the .reference exactly. Bugfix validation will continue to report "does not reproduce" — by design, since master already handles every case.

One open decision for a human, @alexey-milovidov / @novikd: I did not revert #106414 itself. As demonstrated earlier (and reproduced here), #106414 is the non-correlated EXISTS crash-fix, not correlated-subquery support — reverting it re-breaks the non-correlated case DELETE … WHERE exists((SELECT DISTINCT * LIMIT 452)) (covered by 04305_mutation_in_subquery_column_identifier). Correlated subqueries are already disallowed on master via assertEmpty. Reverting #106414 is a separate change from this PR's net diff; if you still want it, it should be its own PR with 04305 updated accordingly.

@alexey-milovidov

Copy link
Copy Markdown
Member

CI finished on HEAD a22dc549f0a (test-only). The PR is ready: net diff is just the 04303_stid_4697_4326_mutation_exists_column_identifier test, MutationsInterpreter.cpp is byte-identical to master, AI Review is ✅ Approve, and 04303 passed everywhere it actually ran (Fast test, arm_darwin, every stateless lane, and the flaky-check shards on asan/msan/tsan/debug). Bugfix validation is correctly SKIPPED now that the category is CI Fix or Improvement.

The 3 remaining reds are all unrelated flakes — this PR adds only a stateless SQL test (no C++/Keeper changes):

  • Stress test (amd_tsan / arm_tsan) — Hung check failed, possible deadlock found → known master-wide flake Hung check failed, possible deadlock found #107941 (the report already links it). The hung-query thread dumps reference mt_with_pk / 04411_t, never 04303.
  • Fast test (arm_darwin) — 03231_keeper_cpr_mvr_commands → a Keeper-client/Darwin flake unrelated to mutations; it also failed on master (PR 0) on 2026-06-26 with the same "having stderror" signature. No tracking issue yet.

@groeneai, could you confirm/track the 03231_keeper_cpr_mvr_commands arm_darwin flake (also seen on master 2026-06-26) and provide a fix in a separate PR if warranted? It's not caused by this test-only change. Otherwise the PR is good to merge once the flaky reds are re-run/overridden.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov Confirmed and tracked. 03231_keeper_cpr_mvr_commands on Fast test (arm_darwin) is the same benign keeper-client teardown flake as 03135_keeper_client_find_commands, and a fix already exists and is approved.

Root cause (stdout was correct on that run; only stderr tripped the harness): at clickhouse-keeper-client process exit the one-shot -q client destroys its zkutil::ZooKeeper, and Coordination::ZooKeeper::finalize calls Poco::Net::SocketImpl::shutdown() on an already-disconnected socket. On macOS that raises Net Exception: Socket is not connected (errno 57 / ENOTCONN), which gets logged to stderr. Fast test treats any stderr as failure ("having stderror"). Unrelated to this test-only change (no C++/Keeper code here).

Fix: #107438 ("Do not log benign ENOTCONN on socket shutdown during ZooKeeper finalize") downgrades exactly this log to TRACE at both socket.shutdown() sites in ZooKeeper::finalize. It is engine-side, so it covers the whole keeper-client teardown family (03135, 03231, ...) on arm_darwin. Approved by @alesapin on 2026-06-19, OPEN awaiting merge.

CIDB (30d, Fast test (arm_darwin)): family is arm_darwin-only across unrelated PRs, 0 on master. The 03231 hit on master 2026-06-26 was a different benign cause (LLVM Profile Error: Invalid profile data to merge injected into stdout on the coverage lane), not this stderr flake.

No separate PR needed here. #106025 is good to merge once the flaky reds are re-run/overridden.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a22dc54

CI fully finished (Finish Workflow: success). This PR is test-only (ALTER UPDATE column-identifier regression), APPROVED by @ alexey-milovidov + @ KochetovNicolai. Every failure has an owner; none is PR-caused.

Check / test Reason Owner
Fast test (arm_darwin) / 03231_keeper_cpr_mvr_commands flaky: benign ENOTCONN stderr at keeper-client teardown (keeper-client family, 17 hits / 17 PRs / 30d, arm_darwin only) #107438 (ours, open, approved by @ alesapin)
Stress test (amd_tsan) + (arm_tsan) / "Hung check failed, possible deadlock found" deadlock: #107941 deep-nested formatQuery literal slowness (per @ alexey-milovidov FYI 2026-06-30) #108892 (external, open) — perf fix in flight; hung-check family also #108212 (ours, merged)
Mergeable Check / PR aggregator rollup of the rows above

Session id: cron:our-pr-ci-monitor:20260630-163000

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a22dc54

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 03231_keeper_cpr_mvr_commands flaky (macOS-only benign ENOTCONN stderr noise at keeper-client ZooKeeper finalize; command output correct; 0 master, hits unrelated PRs) #107438 (ours, open)
Stress test (amd_tsan) / Hung check failed, possible deadlock found chronic stress-shutdown deadlock family (not PR-caused; this PR is a test-only regression test) #108212 (ours, merged) / #105905 (ours, open)
Stress test (arm_tsan) / Hung check failed, possible deadlock found same hung-check family #108212 (ours, merged) / #105905 (ours, open)

This PR's diff is test-only (tests/queries/0_stateless/04303_stid_4697_4326_mutation_exists_column_identifier.{sql,reference}); PR-caused gate = ZERO. The 03231 keeper-client flake and the stress Hung-check are both pre-existing trunk issues each owned by an open fixing PR above.

Session id: cron:our-pr-ci-monitor:20260701-043000

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 75ede47

CI fully finished on head 75ede47bc230 (Finish Workflow: success, Mergeable Check: success). This PR is test-only (ALTER UPDATE column-identifier regression). Every failure below has an owner.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) — ThreadSanitizer data race (STID 1003-358c) data race in UniqExactSet::merge -> HashSetTable::merge -> HashTable::resize (parallel uniqExact two-level merge); chronic trunk, NOT PR-caused (this diff is test-only; race spans 7 unrelated PRs + 1 master/30d) #109389 (ours, merged 2026-07-07) — the failing build (06:35Z) predated the fix merge (10:49Z); merged master @ 0c72215052071 to pick it up. Zero STID 1003-358c recurrences anywhere after the fix merged.

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

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.18% 86.19% +0.02%
Functions 91.50% 91.50% +0.00%
Branches 78.73% 78.77% +0.04%

Changed lines: No C/C++ source files changed — skipping uncovered code analysis.

Newly covered by added/modified tests: 117 line(s), 9 function(s) across 43 file(s) · Details

Top files
  • src/Dictionaries/IPAddressDictionary.h: 9 line(s), 7 function(s)
  • src/Interpreters/FileCache/EvictionCandidates.cpp: 9 line(s)
  • src/Functions/FunctionCustomWeekToDateOrDate32.h: 6 line(s)
  • src/Functions/h3UnidirectionalEdgeIsValid.cpp: 6 line(s)
  • src/Functions/FunctionsCodingIP.cpp: 5 line(s)

Full report

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0c72215

Clean CI. The master-merge that picked up #109389 (uniqExact two-level parallel-merge TSan fix) resolved the prior head's sole failure. No failures on this head; nothing PR-caused.

Check / test Reason Owner / fixing PR
(all checks) — green — 62 pass / 110 skipped, Finish Workflow + Mergeable pass

Prior head 75ede47 carried Stress test (arm_tsan) STID 1003-358c (UniqExactSet::merge TSan data race, chronic trunk, not PR-caused), owned by #109389 (ours, merged 2026-07-07). Merging master to pick it up cleared it — 0 recurrences on this head.

Session id: cron:our-pr-ci-monitor:20260709-000000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 9, 2026
Merged via the queue into ClickHouse:master with commit bf54493 Jul 9, 2026
175 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 9, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 10, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 10, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 10, 2026
Backport #106025 to 26.6: Fix LOGICAL_ERROR "Column identifier is already registered" in ALTER UPDATE with EXISTS
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Per @KochetovNicolai and @novikd review on PR ClickHouse#106025:
correlated subqueries in `ALTER UPDATE` / `ALTER DELETE` are
deprecated. Non-correlated `EXISTS` continues to work via the
existing `createUniqueAliasesIfNecessary` fix in
`buildSubqueryPlansForSetsAndAdd`.

A new in-depth visitor walks the resolved mutation expression
right after `QueryAnalyzer::resolve` and throws `NOT_IMPLEMENTED`
on any `QueryNode` / `UnionNode` that has correlated columns.
This produces a clean user error instead of letting the query
reach the planner where it would previously raise the
`Logical error: 'Column identifier ... is already registered'`
exception (and abort the server in debug / sanitizer builds).

Test extends `04303_stid_4697_4326_mutation_exists_column_identifier`
with three correlated cases that must error with `NOT_IMPLEMENTED`:
correlated `EXISTS` over `system.one`-style subquery, correlated
`EXISTS` over `numbers(10)`, and correlated `EXISTS` inside
`ALTER DELETE`. Existing non-correlated `EXISTS` and `NOT EXISTS`
cases are kept and continue to pass.

PR-relatedness: pivot of PR ClickHouse#106025 in response to the team's
preferred direction (deprecate vs. fix-the-crash). The IN-function
gate at `src/Analyzer/Resolve/resolveFunction.cpp:1139` already
covers correlated `IN` arguments globally; this change adds the
parallel mutation-scope gate for `EXISTS` and any other correlated
subquery shape that survives analyzer rewrites.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ions

Per @novikd's review (ClickHouse#106025
"remove the code added in ClickHouse#106414 (keep the test)") and the unresolved
thread asking to reuse `traverseQueryTree` instead of a new visitor.

Both halves of this PR's earlier code are now redundant with `master`:

* The non-correlated `EXISTS` crash-fix (`createUniqueAliasesIfNecessary`
  on the detached subquery) landed independently on `master` via ClickHouse#106414
  (`MutationsInterpreter.cpp`).
* Correlated subqueries in mutations are already rejected with
  `NOT_IMPLEMENTED` on `master` by `correlated_subtrees.assertEmpty("in
  mutation filter"/"in mutation update")` in
  `MutationsInterpreter::prepareMutationStages`.

This PR's `ValidateNoCorrelatedSubqueryVisitor` therefore added no
behavior over `master`; `Bugfix validation` confirms the regression test
`04303_stid_4697_4326_mutation_exists_column_identifier` already passes on
the unfixed base, so every case it covers is handled by the existing
`master` code. Restore `MutationsInterpreter.cpp` to `master` and keep only
the regression test.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-mutations-column-identifier

Fix LOGICAL_ERROR "Column identifier is already registered" in ALTER UPDATE with EXISTS
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-ci pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

7 participants