fix(query): prevent stack overflow in CTE processing with recursive annotations #18588
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I hereby agree to the terms of the CLA available at: https://docs.databend.com/dev/policies/cla/
Summary
Fix stack overflow in CTE processing that caused segmentation faults when processing complex queries with many UNION operations.
🐛 Problem Description
PR #18577 introduced a regression causing segmentation faults when processing complex CTE (Common Table Expression) queries with many UNION operations. The issue manifests as stack overflow due to deep recursive calls during query binding and AST traversal.
Root Cause
The
m_cte_to_temp_table()
function performs double recursion:drive_mut()
bind_query()
For queries with 150+ UNION operations, this creates ~300 levels of recursive calls, exceeding stack limits.
🔧 Solution
Following the pattern established in PR #18268, this fix adds
#[recursive::recursive]
annotations to key CTE processing functions. Therecursive
library automatically grows stack size when needed, preventing overflow.Modified Functions
bind_query()
- Main query binding entry pointm_cte_to_temp_table()
- CTE temporary table creationcompute_cte_ref_count()
- CTE reference countingbind_cte_definition()
- CTE definition bindingTableNameReplacer
visitor methods - AST traversal for name replacementTests
Type of change
This change is