Skip to main content

risingwave_frontend/expr/
asynchronous.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 risingwave_expr::sig::FUNCTION_REGISTRY;
16
17use super::{
18    Expr, ExprImpl, ExprVisitor, FunctionCall, FunctionCallWithLambda, UserDefinedFunction,
19    default_visit_expr,
20};
21
22#[derive(Default)]
23struct AsyncAnalyzer(bool);
24
25impl ExprVisitor for AsyncAnalyzer {
26    fn visit_expr(&mut self, expr: &ExprImpl) {
27        if !self.0 {
28            default_visit_expr(self, expr);
29        }
30    }
31
32    fn visit_function_call(&mut self, call: &FunctionCall) {
33        let args = call
34            .inputs()
35            .iter()
36            .map(Expr::return_type)
37            .collect::<Vec<_>>();
38        // SOME/ALL are wrappers built outside the registry; their children determine their mode.
39        self.0 |= FUNCTION_REGISTRY
40            .get(call.func_type(), &args, &call.return_type())
41            .is_ok_and(|sig| sig.is_async);
42        if self.0 {
43            return;
44        }
45        for input in call.inputs() {
46            self.visit_expr(input);
47            if self.0 {
48                break;
49            }
50        }
51    }
52
53    fn visit_function_call_with_lambda(&mut self, call: &FunctionCallWithLambda) {
54        self.visit_function_call(&call.to_full_function_call());
55    }
56
57    fn visit_user_defined_function(&mut self, _: &UserDefinedFunction) {
58        // All scalar UDF runtimes implement AsyncExpression, including local language runtimes.
59        self.0 = true;
60    }
61}
62
63impl ExprImpl {
64    /// Whether evaluating this scalar expression may suspend. Keep the whole tree together:
65    /// extracting async children from CASE/COALESCE/AND/OR would change conditional evaluation.
66    pub fn is_async(&self) -> bool {
67        let mut analyzer = AsyncAnalyzer::default();
68        analyzer.visit_expr(self);
69        analyzer.0
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use risingwave_common::types::{DataType, JsonbVal, StructType};
76    use risingwave_expr::expr::{BoxedExpression, build_from_prost};
77
78    use super::*;
79    use crate::expr::{ExprType, InputRef};
80
81    #[test]
82    fn ai_decide_and_its_lazy_parent_are_async() {
83        let result_type: DataType = StructType::new([("q", DataType::Float64)]).into();
84        let decide: ExprImpl = FunctionCall::new_unchecked(
85            ExprType::AiDecide,
86            vec![
87                InputRef::new(0, DataType::Jsonb).into(),
88                ExprImpl::literal_varchar("http://127.0.0.1:1/evaluate".into()),
89                ExprImpl::literal_varchar("test-model".into()),
90                ExprImpl::literal_jsonb(JsonbVal::from(serde_json::json!({
91                    "q": {"type": "noul", "instructions": "Resolved?"}
92                }))),
93                ExprImpl::literal_varchar("test-key".into()),
94            ],
95            result_type.clone(),
96        )
97        .into();
98        let conditional = FunctionCall::new_unchecked(
99            ExprType::Case,
100            vec![
101                InputRef::new(1, DataType::Boolean).into(),
102                decide.clone(),
103                ExprImpl::literal_null(result_type.clone()),
104            ],
105            result_type,
106        )
107        .into();
108        for expr in [decide, conditional] {
109            assert!(expr.is_async());
110            assert!(matches!(
111                build_from_prost(&expr.to_expr_proto()).unwrap(),
112                BoxedExpression::Async(_)
113            ));
114        }
115    }
116
117    #[test]
118    fn classification_matches_built_expressions() {
119        let sleep: ExprImpl = FunctionCall::new_unchecked(
120            ExprType::PgSleep,
121            vec![ExprImpl::literal_f64(0.0)],
122            DataType::Int32,
123        )
124        .into();
125        let nested: ExprImpl = FunctionCall::new_unchecked(
126            ExprType::Case,
127            vec![
128                ExprImpl::literal_bool(false),
129                sleep.clone(),
130                ExprImpl::literal_int(1),
131            ],
132            DataType::Int32,
133        )
134        .into();
135        let sync: ExprImpl = FunctionCall::new_unchecked(
136            ExprType::Add,
137            vec![
138                InputRef::new(0, DataType::Int32).into(),
139                ExprImpl::literal_int(1),
140            ],
141            DataType::Int32,
142        )
143        .into();
144        for expr in [sleep, nested, sync] {
145            let built = build_from_prost(&expr.to_expr_proto()).unwrap();
146            assert_eq!(expr.is_async(), matches!(built, BoxedExpression::Async(_)));
147        }
148
149        let embedding: ExprImpl = FunctionCall::new_unchecked(
150            ExprType::OpenaiEmbedding,
151            vec![
152                ExprImpl::literal_null(DataType::Jsonb),
153                ExprImpl::literal_varchar("text".into()),
154            ],
155            DataType::Float32.list(),
156        )
157        .into();
158        assert!(embedding.is_async());
159        let udf: ExprImpl = UserDefinedFunction::from_expr_proto(
160            &risingwave_pb::expr::UserDefinedFunction {
161                name: "test_udf".into(),
162                ..Default::default()
163            },
164            DataType::Int32,
165        )
166        .unwrap()
167        .into();
168        assert!(udf.is_async());
169    }
170}