Skip to main content

vortex_expr/proto/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod foreign;
5
6pub use foreign::*;
7use itertools::Itertools;
8use vortex_array::proto::expr as pb;
9use vortex_array::scalar_fn::ScalarFnId;
10use vortex_array::scalar_fn::session::ScalarFnSessionExt;
11use vortex_error::VortexResult;
12use vortex_error::vortex_ensure;
13use vortex_error::vortex_err;
14use vortex_session::VortexSession;
15
16use crate::Expression;
17use crate::expression::unbound_variable;
18
19pub trait ExprSerializeProtoExt {
20    /// Serialize the expression to its protobuf representation.
21    fn serialize_proto(&self) -> VortexResult<pb::Expr>;
22}
23
24/// The wire id for [`Expression::Root`], retained from when `Root` was a scalar function so that
25/// already-serialized expressions keep round-tripping.
26pub(crate) const ROOT_ID: &str = "vortex.root";
27
28const MAX_EXPR_PROTO_DEPTH: usize = 100;
29
30fn ensure_proto_depth(depth: usize) -> VortexResult<()> {
31    vortex_ensure!(
32        depth <= MAX_EXPR_PROTO_DEPTH,
33        "expression nesting depth exceeds the maximum of {MAX_EXPR_PROTO_DEPTH}"
34    );
35    Ok(())
36}
37
38impl ExprSerializeProtoExt for Expression {
39    fn serialize_proto(&self) -> VortexResult<pb::Expr> {
40        self.serialize_proto_at_depth(1)
41    }
42}
43
44impl Expression {
45    fn serialize_proto_at_depth(&self, depth: usize) -> VortexResult<pb::Expr> {
46        ensure_proto_depth(depth)?;
47        if let Expression::Variable(name) = self {
48            return Err(unbound_variable(name));
49        }
50        let Some(scalar_fn) = self.as_scalar() else {
51            return Ok(pb::Expr {
52                id: ROOT_ID.to_string(),
53                children: vec![],
54                metadata: Some(vec![]),
55            });
56        };
57
58        let children = self
59            .children()
60            .iter()
61            .map(|child| child.serialize_proto_at_depth(depth + 1))
62            .try_collect()?;
63
64        let metadata = scalar_fn.options().serialize()?.ok_or_else(|| {
65            vortex_err!(
66                "Expression '{}' is not serializable: {}",
67                scalar_fn.id(),
68                self
69            )
70        })?;
71
72        Ok(pb::Expr {
73            id: scalar_fn.id().to_string(),
74            children,
75            metadata: Some(metadata),
76        })
77    }
78}
79
80impl Expression {
81    pub fn from_proto(expr: &pb::Expr, session: &VortexSession) -> VortexResult<Expression> {
82        Self::from_proto_at_depth(expr, session, 1)
83    }
84
85    fn from_proto_at_depth(
86        expr: &pb::Expr,
87        session: &VortexSession,
88        depth: usize,
89    ) -> VortexResult<Expression> {
90        ensure_proto_depth(depth)?;
91        // Root is not a registered scalar fn, so it must be resolved before the registry lookup.
92        if expr.id == ROOT_ID {
93            vortex_ensure!(
94                expr.children.is_empty(),
95                "root expression must have no children, got {}",
96                expr.children.len()
97            );
98            return Ok(Expression::Root);
99        }
100
101        #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
102        let expr_id = ScalarFnId::new(expr.id.as_str());
103        let children = expr
104            .children
105            .iter()
106            .map(|e| Expression::from_proto_at_depth(e, session, depth + 1))
107            .collect::<VortexResult<Vec<_>>>()?;
108
109        let scalar_fn = if let Some(vtable) = session.scalar_fns().registry().get(&expr_id) {
110            vtable.deserialize(expr.metadata(), session)?
111        } else if session.allows_unknown() {
112            ForeignScalarFnVTable::make_scalar_fn(expr_id, expr.metadata().to_vec(), children.len())
113        } else {
114            return Err(vortex_err!("unknown expression id: {}", expr_id));
115        };
116
117        Expression::try_new(scalar_fn, children)
118    }
119}
120
121/// Deserialize a [`Expression`] from the protobuf representation.
122#[deprecated(note = "Use Expression::from_proto instead")]
123pub fn deserialize_expr_proto(
124    expr: &pb::Expr,
125    session: &VortexSession,
126) -> VortexResult<Expression> {
127    Expression::from_proto(expr, session)
128}
129
130#[cfg(test)]
131mod tests {
132    use std::sync::LazyLock;
133
134    use prost::Message;
135    use vortex_array::proto::expr as pb;
136    use vortex_array::scalar_fn::session::ScalarFnSession;
137    use vortex_error::VortexResult;
138    use vortex_session::VortexSession;
139
140    use super::ExprSerializeProtoExt;
141    use super::MAX_EXPR_PROTO_DEPTH;
142    use crate::Expression;
143    use crate::and;
144    use crate::eq;
145    use crate::get_item;
146    use crate::lit;
147    use crate::lt;
148    use crate::not;
149    use crate::or;
150    use crate::root;
151
152    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
153        let session = VortexSession::empty().with::<ScalarFnSession>();
154        session.allow_unknown();
155        session
156    });
157
158    #[test]
159    fn expression_serde() {
160        let expr: Expression = or(
161            and(lt(lit(1), get_item("a", root())), lit(1)),
162            eq(lit(1), root()),
163        );
164
165        let s_expr = expr.serialize_proto().unwrap();
166        let buf = s_expr.encode_to_vec();
167        let s_expr = pb::Expr::decode(buf.as_slice()).unwrap();
168        let deser_expr = Expression::from_proto(&s_expr, &VortexSession::empty()).unwrap();
169
170        assert_eq!(&deser_expr, &expr);
171    }
172
173    #[test]
174    fn unknown_expression_id_allow_unknown() {
175        let expr_proto = pb::Expr {
176            id: "vortex.test.foreign_scalar_fn".to_string(),
177            metadata: Some(vec![1, 2, 3, 4]),
178            children: vec![root().serialize_proto().unwrap()],
179        };
180
181        let expr = Expression::from_proto(&expr_proto, &SESSION).unwrap();
182        assert_eq!(
183            expr.as_scalar().map(|f| f.id().as_ref().to_string()),
184            Some("vortex.test.foreign_scalar_fn".to_string())
185        );
186
187        let roundtrip = expr.serialize_proto().unwrap();
188        assert_eq!(roundtrip.id, expr_proto.id);
189        assert_eq!(roundtrip.metadata(), expr_proto.metadata());
190        assert_eq!(roundtrip.children, expr_proto.children);
191    }
192
193    fn nested_not(depth: usize) -> Expression {
194        (1..depth).fold(root(), |expr, _| not(expr))
195    }
196
197    fn nested_not_proto(depth: usize) -> VortexResult<pb::Expr> {
198        let not_proto = not(root()).serialize_proto()?;
199        Ok(
200            (1..depth).fold(root().serialize_proto()?, |child, _| pb::Expr {
201                children: vec![child],
202                ..not_proto.clone()
203            }),
204        )
205    }
206
207    #[test]
208    fn serialize_proto_depth_limit() -> VortexResult<()> {
209        nested_not(MAX_EXPR_PROTO_DEPTH).serialize_proto()?;
210
211        let err = nested_not(MAX_EXPR_PROTO_DEPTH + 1)
212            .serialize_proto()
213            .unwrap_err();
214        assert!(err.to_string().contains("nesting depth"), "{err}");
215        Ok(())
216    }
217
218    #[test]
219    fn from_proto_depth_limit() -> VortexResult<()> {
220        let expr = Expression::from_proto(&nested_not_proto(MAX_EXPR_PROTO_DEPTH)?, &SESSION)?;
221        assert_eq!(expr, nested_not(MAX_EXPR_PROTO_DEPTH));
222
223        let err = Expression::from_proto(&nested_not_proto(MAX_EXPR_PROTO_DEPTH + 1)?, &SESSION)
224            .unwrap_err();
225        assert!(err.to_string().contains("nesting depth"), "{err}");
226        Ok(())
227    }
228
229    #[test]
230    fn encoded_proto_depth_limit() -> VortexResult<()> {
231        let expr = nested_not(MAX_EXPR_PROTO_DEPTH);
232        let buf = expr.serialize_proto()?.encode_to_vec();
233        let decoded = pb::Expr::decode(buf.as_slice())?;
234        assert_eq!(Expression::from_proto(&decoded, &SESSION)?, expr);
235
236        let buf = nested_not_proto(MAX_EXPR_PROTO_DEPTH + 1)?.encode_to_vec();
237        let decoded = pb::Expr::decode(buf.as_slice())?;
238        let err = Expression::from_proto(&decoded, &SESSION).unwrap_err();
239        assert!(err.to_string().contains("nesting depth"), "{err}");
240        Ok(())
241    }
242
243    #[test]
244    fn deeply_nested_expression_errors() -> VortexResult<()> {
245        let depth = 10_000;
246        assert!(nested_not(depth).serialize_proto().is_err());
247
248        let mut proto = nested_not_proto(depth)?;
249        assert!(Expression::from_proto(&proto, &SESSION).is_err());
250        while let Some(child) = proto.children.pop() {
251            proto = child;
252        }
253        Ok(())
254    }
255}