Skip to content

Reject correlated recursive CTE instead of aborting with a logical error - #109863

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-recursive-cte-correlated-subquery
Jul 12, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-recursive-cte-correlated-subquery

Conversation

@groeneai

@groeneai groeneai commented Jul 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #80564

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

Fix a LOGICAL_ERROR (query tree node does not have valid source node) when a recursive CTE resolved an identifier from an outer scope as a correlated column (with allow_experimental_correlated_subqueries = 1). Such queries now return a clear UNSUPPORTED_METHOD error.

Description

A recursive CTE is planned as a fixed-point over a temporary table, so it has no per-call-site substitution mechanism and cannot be correlated to an outer scope. When an identifier in the recursive term leaked to an enclosing recursive CTE's column (this happens, for example, when the base term is a scalar subquery whose projection column is not named the same as the recursive-term identifier), resolution bound it as a correlated column whose source is not part of the subquery. That produced a ColumnNode with a dangling source node, which later aborted during planning in ColumnNode::getColumnSource() (CollectSourceColumnsVisitor, Planner/CollectTableExpressionData.cpp).

The fix detects the correlated recursive query during resolution and throws a clean UNSUPPORTED_METHOD error, mirroring the existing "Materialized CTE cannot be correlated" guard.

Found by the AST fuzzer.

Minimal reproducer (requires enable_analyzer = 1, allow_experimental_correlated_subqueries = 1):

SELECT count(*)
FROM (WITH RECURSIVE t AS (SELECT toUInt64(1) AS n UNION ALL SELECT n + 1 FROM t WHERE n < 5) SELECT * FROM t) AS t
WHERE n < (SELECT count(*) FROM (WITH RECURSIVE s AS (SELECT (SELECT toUInt64(1) AS n) UNION ALL SELECT n + 1 FROM s WHERE n < 3) SELECT * FROM s) AS s);

Version info

  • Merged into: 26.7.1.835 (included in 26.7 and later)

A recursive CTE is planned as a fixed-point over a temporary table, so it
has no per-call-site substitution mechanism and cannot be correlated to an
outer scope. When an identifier in a recursive term leaked to an enclosing
recursive CTE column (allow_experimental_correlated_subqueries=1), resolution
bound it as a correlated column whose source is not part of the subquery,
producing a dangling source node during planning and aborting with
'query tree node does not have valid source node' (LOGICAL_ERROR).

Detect the correlated recursive query during resolution and throw a clean
UNSUPPORTED_METHOD error, matching the existing 'Materialized CTE cannot be
correlated' guard.

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

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. clickhouse-local --allow_experimental_correlated_subqueries=1 -q "<recursive-CTE query above>" aborts (SIGABRT, exit 134) every time on HEAD.
b Root cause explained? A recursive CTE is planned as a fixed-point over a temp table (no per-call-site substitution). With correlated subqueries enabled, an identifier in the recursive term that has no local binding leaks to an enclosing recursive CTE's column and is bound as a correlated column. That ColumnNode's source is not part of the subquery, so during planning CollectSourceColumnsVisitor calls ColumnNode::getColumnSource(), the weak source pointer is null, and it throws LOGICAL_ERROR (abort in debug/sanitizer).
c Fix matches root cause? Yes. After resolving each recursive query, if it became correlated (isCorrelated()), reject with UNSUPPORTED_METHOD before the dangling source can reach planning. Mirrors the existing "Materialized CTE cannot be correlated" guard.
d Test intent preserved / new tests added? New test 04401_recursive_cte_correlated_subquery added: asserts the correlated recursive CTE now errors (serverError UNSUPPORTED_METHOD) and that valid nested/independent recursive CTEs and valid non-recursive correlated subqueries still work.
e Demonstrated in both directions? Yes. Pre-fix binary: exit 134 (abort). Post-fix binary: Code: 1 ... Recursive CTE 's' cannot be correlated (UNSUPPORTED_METHOD), exit 1. Verified on a master-base build.
f Fix is general, not a narrow patch? The guard covers all recursive query terms (i=1..N) of the CTE, not just the scalar-subquery-base variant the fuzzer hit. The base (non-recursive) term correlated case is genuinely supported (verified working) and correctly not caught.
g Generalizes across inputs? Verified with direct-n reference, scalar-subquery base, renamed inner CTE, and LowCardinality/toLowCardinality fuzzed variants — all now return the clean error. Non-correlated recursive CTEs and normal correlated subqueries unaffected.
h Backward compatible? Yes. Only converts a debug/sanitizer abort into a normal exception. Release builds already threw a (mis-planned) error; no format/setting/behavior change for valid queries. Feature is gated behind experimental allow_experimental_correlated_subqueries.
i Invariants/contracts preserved? Yes. Upholds the analyzer invariant that every ColumnNode reaching planning has a valid source; rejects the unsupported construct at resolution time instead of letting a dangling source propagate. Existing recursive-CTE Postgres regression tests still pass.

Session id: cron:clickhouse-worker-slot-1:20260709-043700

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vdimir — could you review? Rejects a correlated recursive CTE (allow_experimental_correlated_subqueries=1) with a clean UNSUPPORTED_METHOD error instead of aborting with a dangling-source-node LOGICAL_ERROR, mirroring the existing Materialized-CTE-cannot-be-correlated guard. @ novikd owns the correlated-subqueries path.

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

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [db35f01]

Summary: ✅


AI Review

Summary

This PR hardens recursive CTE resolution by rejecting correlated seed terms as well as correlated recursive members before planning, so unsupported recursive correlations now fail with UNSUPPORTED_METHOD instead of reaching a dangling-source LOGICAL_ERROR. I re-checked the current diff, the surrounding QueryAnalyzer/planner/RecursiveCTESource path, the existing review thread, and the latest Praktika report; the previously reported seed-term gap is fixed and I did not find a remaining issue in the changed code.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 9, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
The prior guard only rejected a correlated recursive member. A recursive CTE
whose seed (non-recursive) term is correlated to an outer scope still passed:
Planner::buildPlanForUnionNode lowers the whole union to ReadFromRecursiveCTEStep
and RecursiveCTESource::buildStepExecutor re-runs the seed with only the temporary
CTE table injected, so there is no mechanism to supply the outer-scope binding.
That left the same unsupported contract in place and aborted with a LOGICAL_ERROR.

Check isCorrelated() on the resolved non-recursive query as well and throw the
same UNSUPPORTED_METHOD error. Add a seed-only-correlated regression test.

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

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch. Fixed in b679774.

Added the same rejection for a correlated seed term: after resolving the non-recursive query (queries_nodes[0]) in resolveUnion, check its isCorrelated() and throw the same UNSUPPORTED_METHOD ("Recursive CTE '...' cannot be correlated"). This covers both a correlated non_recursive_query directly and, transitively, a correlated union seed.

Verified locally on the PR binary (debug):

  • Seed-only shape WITH RECURSIVE s AS (SELECT n AS m UNION ALL SELECT m + 1 FROM s WHERE m < 3) referencing outer n: aborted (SIGABRT, exit 134) without the seed guard; returns clean UNSUPPORTED_METHOD with it.
  • Correlated recursive-member shape: still rejected.
  • Non-correlated nested recursive CTE and correlated non-recursive inner subquery: still work (2, 0).

Extended tests/queries/0_stateless/04401_recursive_cte_correlated_subquery.sql with a seed-only-correlated case asserting serverError UNSUPPORTED_METHOD.

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b679774

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
Integration tests (amd_msan, 6/8) / test_rabbitmq_mv_combo chronic flaky integration a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
Stress test (arm_asan_ubsan) / Hung check failed, possible deadlock deadlock family #108212 (ours, merged) / #105905 (ours, merged)

Neither is PR-caused: PR #109863 touches only src/Analyzer/Resolve/QueryAnalyzer.cpp and one stateless test; both failures are unrelated chronic trunk/flaky signatures.

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

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_rabbitmq_mv_combo integration flake (Integration tests amd_msan): #109892

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b679774

Every failure below has an owner. The original AST fuzzer STID 2945-38b2 (which this PR fixes) did not recur on this head. The 3 CANCELLED coverage/binary/integration shards are not failures.

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 6/8) / test_rabbitmq_mv_combo flaky (11 master + 15 unrelated PRs, 30d) #109892 (ours, open)
Stress test (arm_asan_ubsan) / Hung check, possible deadlock deadlock (chronic trunk family, 397 master/30d) #108212 (ours, merged) / #105905 (ours, merged)

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 12, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, all CI fixes are merged, please update the branch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Branch updated to db35f01 (merged current master), CI rerunning.

@clickhouse-gh

clickhouse-gh Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 47.50% 85.80% +38.30%
Functions 62.90% 92.70% +29.80%
Branches 36.20% 77.90% +41.70%

Changed lines: Changed C/C++ lines covered: 20/24 (83.33%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — db35f01

CI fully finished on the updated branch (merged current master per @alexey-milovidov). All checks green: 156 SUCCESS + 18 SKIPPED, Finish Workflow + Mergeable Check + CH Inc sync all pass. No failures.

Session id: cron:our-pr-ci-monitor:20260712-183000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 12, 2026
Merged via the queue into ClickHouse:master with commit 724f492 Jul 12, 2026
176 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 12, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @alexey-milovidov — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Reviewed #110193 — LGTM. Coverage gap is real (only that PR exercises the seed-is-UNION resolveUnion branch; no existing recursive-CTE test uses a UNION seed), output verified against master. I lack label write access, so the can be tested label is left for a maintainer. Review details on #110193.

pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Jul 18, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…sive-cte-correlated-subquery

Reject correlated recursive CTE instead of aborting with a logical error
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants