Repository navigation
Conversation
`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]>
|
cc @azat @KochetovNicolai — could you review? Small fix in a shared visitor ( cc @PedroTadim — per your directive on #105370. Pre-PR validation gate
Session: cron:clickhouse-ci-task-worker:20260520-133000 |
|
Workflow [PR], commit [683d9cf] Summary: ❌
AI ReviewSummaryThis PR fixes the analyzer-to-AST round trip for PR Metadata
Final VerdictStatus: ✅ Approve Only metadata cleanup remains: switch the changelog category to |
|
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:
// 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 I'd suggest fixing the producer instead, one line at select_query->recursive_with = is_recursive_with && hasWith();(or move the assignment inside the existing 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:
|
CI ledger — covered SHA:
|
| 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
|
Note: my prior CI ledger comment misnamed the SHA. Correct ledger for current HEAD: CI ledger — covered SHA:
|
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]>
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260605-014700 |
|
@azat — applied your suggested producer fix in I also added a stateless regression Confirmed locally on a clang-21 ASan+UBSan build: with the producer fix reverted, the gtest trips |
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]>
Pre-PR validation gate (fixup commit 6cef301)This fixup corrects the PR-caused failure of the new regression test
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]>
Pre-PR validation gate (fixup commit
|
| # | 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]>
Pre-PR validation gate(test-hygiene fixup
Session id: cron:clickhouse-worker-slot-16:20260611-020200 |
|
CI finished on The one remaining failure is not caused by this PR (a test-only
Ready for review. The producer fix ( |
| if (typeid_cast<ASTWithElement *>(child.get())) | ||
| with_aliases.insert(child->as<ASTWithElement>()->name); | ||
| } | ||
| if (auto with = select.with()) |
There was a problem hiding this comment.
Let's remove this, we should have recursive_with only if we have with already
There was a problem hiding this comment.
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]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-18:20260611-141700 |
|
Now squash all commits into one, rebase the description of PR and commits, stick to https://www.linfo.org/rule_of_silence.html principles |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 5/5 (100.00%) | Lost baseline coverage: none · Uncovered code |
bf7a84e
…'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]>
AddDefaultDatabaseVisitor::visit(ASTSelectQuery &, ASTPtr &)guards its WITH-traversal onselect.recursive_withbut then dereferencesselect.with()->childrenunconditionally. The parser only setsrecursive_with = truetogether 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 insideIStorageCluster::readwhen the query reaches the cluster code path with such an AST. Surfaced byBuzzHouse (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::formatImplandQueryTreeBuilder::buildSelectQuery. ValidWITH RECURSIVE x AS ...queries are unaffected.Crash signature (
STID: 3440-3393):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):
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 aSELECTwith therecursive_withflag set but noWITHexpression. Closes #105370.Documentation entry for user-facing changes
Version info
26.6.1.688