Skip to main content

risingwave_frontend/optimizer/rule/stream/
stream_project_split_rule.rs

1// Copyright 2026 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use super::prelude::*;
16use crate::expr::{Expr, ExprImpl, InputRef};
17use crate::optimizer::plan_node::generic::GenericPlanRef;
18use crate::optimizer::plan_node::{PlanTreeNodeUnary, StreamProject, generic};
19
20/// Separate synchronous computations from asynchronous expressions. Column references and literals
21/// do not require a separate synchronous layer. Column references are allowed in both layers to
22/// preserve stream keys, distribution, watermarks and the final output order.
23pub struct StreamProjectSplitRule;
24
25impl Rule<Stream> for StreamProjectSplitRule {
26    fn apply(&self, plan: PlanRef) -> Option<PlanRef> {
27        let project = plan.as_stream_project()?;
28        if !has_mixed_computations(project.exprs()) {
29            return None;
30        }
31
32        let input = project.input();
33        let input_len = input.schema().len();
34        let mut async_exprs: Vec<ExprImpl> = input
35            .schema()
36            .fields()
37            .iter()
38            .enumerate()
39            .map(|(idx, field)| InputRef::new(idx, field.data_type()).into())
40            .collect();
41        let mut sync_core = project.core().clone();
42        sync_core.field_names = project
43            .schema()
44            .fields()
45            .iter()
46            .enumerate()
47            .map(|(idx, field)| (idx, field.name.clone()))
48            .collect();
49        for expr in &mut sync_core.exprs {
50            if expr.is_async() {
51                let result = InputRef::new(async_exprs.len(), expr.return_type()).into();
52                // Move each occurrence exactly once. Never extract children from lazy expressions
53                // and never inline a shared result into multiple consumers.
54                async_exprs.push(std::mem::replace(expr, result));
55            }
56        }
57        debug_assert!(async_exprs.len() > input_len);
58        sync_core.input = StreamProject::new(generic::Project::new(async_exprs, input))
59            .with_noop_update_hint(false)
60            .into();
61        Some(
62            StreamProject::new(sync_core)
63                .with_noop_update_hint(project.noop_update_hint())
64                .into(),
65        )
66    }
67}
68
69pub(super) fn is_trivial_expr(expr: &ExprImpl) -> bool {
70    matches!(expr, ExprImpl::InputRef(_) | ExprImpl::Literal(_))
71}
72
73pub(super) fn has_mixed_computations(exprs: &[ExprImpl]) -> bool {
74    exprs.iter().any(ExprImpl::is_async)
75        && exprs
76            .iter()
77            .any(|expr| !is_trivial_expr(expr) && !expr.is_async())
78}
79
80impl StreamProjectSplitRule {
81    pub fn create() -> BoxedRule {
82        Box::new(Self)
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use risingwave_common::catalog::{Field, Schema};
89    use risingwave_common::types::DataType;
90    use risingwave_common::util::iter_util::ZipEqFast;
91
92    use super::*;
93    use crate::expr::{ExprType, FunctionCall};
94    use crate::optimizer::optimizer_context::OptimizerContext;
95    use crate::optimizer::plan_node::StreamValues;
96    use crate::optimizer::plan_node::generic::PhysicalPlanRef;
97    use crate::optimizer::rule::StreamProjectMergeRule;
98
99    #[tokio::test]
100    async fn merge_async_result_with_literals() {
101        let input: PlanRef = StreamValues::new(generic::Values::new_with_stream_key(
102            vec![],
103            Schema::new(vec![Field::with_name(DataType::Float64, "seconds")]),
104            OptimizerContext::mock(),
105            vec![0],
106        ))
107        .into();
108        let sleep: ExprImpl = FunctionCall::new_unchecked(
109            ExprType::PgSleep,
110            vec![InputRef::new(0, DataType::Float64).into()],
111            DataType::Int32,
112        )
113        .into();
114        let inner: PlanRef = StreamProject::new(generic::Project::new(
115            vec![InputRef::new(0, DataType::Float64).into(), sleep.clone()],
116            input.clone(),
117        ))
118        .into();
119        let tag = ExprImpl::literal_varchar("tag".into());
120        let null = ExprImpl::literal_null(DataType::Int32);
121        let outer: PlanRef = StreamProject::new(generic::Project::new(
122            vec![
123                InputRef::new(0, DataType::Float64).into(),
124                InputRef::new(1, DataType::Int32).into(),
125                tag.clone(),
126                null.clone(),
127            ],
128            inner.clone(),
129        ))
130        .into();
131        let merged = StreamProjectMergeRule {}.apply(outer.clone()).unwrap();
132        let project = merged.as_stream_project().unwrap();
133        assert_eq!(project.input(), input);
134        assert_eq!(merged.schema(), outer.schema());
135        assert_eq!(merged.stream_key(), outer.stream_key());
136        assert_eq!(merged.distribution(), outer.distribution());
137        assert_eq!(
138            project.exprs(),
139            &vec![InputRef::new(0, DataType::Float64).into(), sleep, tag, null]
140        );
141
142        // Adding literals must not allow a shared async result to be evaluated twice.
143        let duplicate: PlanRef = StreamProject::new(generic::Project::new(
144            vec![
145                InputRef::new(1, DataType::Int32).into(),
146                InputRef::new(1, DataType::Int32).into(),
147                ExprImpl::literal_int(1),
148            ],
149            inner,
150        ))
151        .into();
152        assert!(StreamProjectMergeRule {}.apply(duplicate).is_none());
153    }
154
155    #[tokio::test]
156    async fn split_preserves_nested_evaluation_and_shared_results() {
157        let input: PlanRef = StreamValues::new(generic::Values::new_with_stream_key(
158            vec![],
159            Schema::new(vec![Field::with_name(DataType::Float64, "seconds")]),
160            OptimizerContext::mock(),
161            vec![0],
162        ))
163        .into();
164        let sleep: ExprImpl = FunctionCall::new_unchecked(
165            ExprType::PgSleep,
166            vec![InputRef::new(0, DataType::Float64).into()],
167            DataType::Int32,
168        )
169        .into();
170        // A false CASE branch must not become an unconditional external evaluation.
171        let conditional: ExprImpl = FunctionCall::new_unchecked(
172            ExprType::Case,
173            vec![
174                ExprImpl::literal_bool(false),
175                sleep,
176                ExprImpl::literal_int(9),
177            ],
178            DataType::Int32,
179        )
180        .into();
181        let exprs = vec![
182            conditional.clone(),
183            FunctionCall::new_unchecked(
184                ExprType::IsNull,
185                vec![InputRef::new(0, DataType::Float64).into()],
186                DataType::Boolean,
187            )
188            .into(),
189            InputRef::new(0, DataType::Float64).into(),
190        ];
191        let original: PlanRef = StreamProject::new(generic::Project::new(exprs, input)).into();
192        let split = StreamProjectSplitRule.apply(original.clone()).unwrap();
193        assert_eq!(split.schema(), original.schema());
194        assert_eq!(split.stream_key(), original.stream_key());
195        assert_eq!(split.distribution(), original.distribution());
196        for (before, after) in original
197            .schema()
198            .fields()
199            .iter()
200            .zip_eq_fast(split.schema().fields())
201        {
202            assert_eq!(before.name, after.name);
203        }
204        let outer = split.as_stream_project().unwrap();
205        assert!(outer.exprs().iter().all(|expr| !expr.is_async()));
206        let inner_plan = outer.input();
207        let inner = inner_plan.as_stream_project().unwrap();
208        assert_eq!(
209            inner.exprs(),
210            &vec![InputRef::new(0, DataType::Float64).into(), conditional]
211        );
212        assert!(StreamProjectSplitRule.apply(inner_plan.clone()).is_none());
213        assert!(StreamProjectMergeRule {}.apply(split.clone()).is_none());
214
215        // A later merge must not move an evaluated async result under a lazy branch, even when
216        // the merged project would contain just one (asynchronous) expression.
217        let lazy_consumer = StreamProject::new(generic::Project::new(
218            vec![
219                FunctionCall::new_unchecked(
220                    ExprType::Case,
221                    vec![
222                        ExprImpl::literal_bool(false),
223                        InputRef::new(1, DataType::Int32).into(),
224                        ExprImpl::literal_int(0),
225                    ],
226                    DataType::Int32,
227                )
228                .into(),
229            ],
230            inner_plan,
231        ));
232        assert!(
233            StreamProjectMergeRule {}
234                .apply(lazy_consumer.into())
235                .is_none()
236        );
237
238        // Consumers retain one reference to the evaluated result for each use, rather than
239        // substituting the conditional async tree and performing the call twice.
240        let consumers = StreamProject::new(generic::Project::new(
241            vec![InputRef::new(0, DataType::Int32).into(); 2],
242            split,
243        ));
244        let merged = StreamProjectMergeRule {}.apply(consumers.into()).unwrap();
245        assert!(
246            merged
247                .as_stream_project()
248                .unwrap()
249                .exprs()
250                .iter()
251                .all(|e| !e.is_async())
252        );
253        let lower = merged.as_stream_project().unwrap().input();
254        assert_eq!(
255            lower
256                .as_stream_project()
257                .unwrap()
258                .exprs()
259                .iter()
260                .filter(|e| e.is_async())
261                .count(),
262            1
263        );
264    }
265}