Skip to main content

vortex_expr/analysis/
referenced_field_paths.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_array::dtype::Field;
5use vortex_array::dtype::FieldPath;
6use vortex_array::dtype::FieldPathSet;
7use vortex_array::expr::BoundExpression;
8use vortex_array::expr::traversal::FoldDownContext;
9use vortex_array::expr::traversal::FoldUp;
10use vortex_array::expr::traversal::NodeExt;
11use vortex_array::expr::traversal::NodeFolderContext;
12use vortex_array::scalar_fn::fns::get_item::GetItem;
13use vortex_array::scalar_fn::fns::select::Select;
14use vortex_error::VortexResult;
15use vortex_error::vortex_err;
16
17/// Returns the rooted field paths referenced by an expression.
18///
19/// Iterating the returned set (via [`IntoIterator`]) yields the prefix-minimal covering set: when
20/// one referenced path is a prefix of another, only the prefix is kept. A standalone root
21/// expression is represented by [`FieldPath::root`], which conservatively selects all fields.
22/// Scalar functions other than `GetItem` and `Select` conservatively reference each complete child
23/// output.
24pub fn referenced_field_paths(expr: &BoundExpression) -> VortexResult<FieldPathSet> {
25    let mut collector = ReferencedFieldPaths {
26        field_paths: FieldPathSet::default(),
27    };
28    expr.clone()
29        .fold_context(&vec![FieldPath::root()], &mut collector)?;
30    Ok(collector.field_paths)
31}
32
33/// Threads the set of currently-requested field paths down the expression tree, narrowing it at
34/// each `GetItem`/`Select`, and records the rooted paths reached at each `Root` leaf.
35///
36/// Paths are carried reversed so a `GetItem` can `push` its field instead of prepending it; they
37/// are reversed back to rooted order when recorded at a `Root`, and `Select` reads a path's head
38/// from its last element.
39///
40/// Narrowing is only sound through `GetItem` (a genuine field access) and `Select` (a genuine
41/// column projection). Any other function is opaque—we cannot assume it preserves a field's
42/// provenance—so its children conservatively re-request the whole scope, which is what keeps an
43/// expression like `f($).x` reading every field of `$` rather than just `x`.
44struct ReferencedFieldPaths {
45    field_paths: FieldPathSet,
46}
47
48impl NodeFolderContext for ReferencedFieldPaths {
49    type NodeTy = BoundExpression;
50    type Result = ();
51    type Context = Vec<FieldPath>;
52
53    fn visit_down(
54        &mut self,
55        requested: &Self::Context,
56        node: &BoundExpression,
57    ) -> VortexResult<FoldDownContext<Self::Context, ()>> {
58        if node.is_root() {
59            self.field_paths.extend(
60                requested
61                    .iter()
62                    .map(|path| FieldPath::from_iter(path.parts().iter().rev().cloned())),
63            );
64            return Ok(FoldDownContext::Skip(()));
65        }
66
67        if let Some(field_name) = node
68            .as_scalar()
69            .and_then(|scalar_fn| scalar_fn.as_opt::<GetItem>())
70        {
71            let appended = requested
72                .iter()
73                .map(|path| path.clone().push(Field::Name(field_name.clone())))
74                .collect();
75            return Ok(FoldDownContext::Continue(appended));
76        }
77
78        // Keep requested paths whose head is included, expanding a whole-scope request into one
79        // path per included field.
80        if let Some(selection) = node
81            .as_scalar()
82            .and_then(|scalar_fn| scalar_fn.as_opt::<Select>())
83        {
84            let child_fields = node.children()[0]
85                .dtype()
86                .as_struct_fields_opt()
87                .ok_or_else(|| vortex_err!("Select child is not a struct"))?;
88            let included_fields = selection.normalize_to_included_fields(child_fields.names())?;
89
90            let mut narrowed = Vec::with_capacity(requested.len());
91            for path in requested {
92                if path.is_root() {
93                    narrowed.extend(included_fields.iter().cloned().map(FieldPath::from_name));
94                } else if let Some(Field::Name(field_name)) = path.parts().last()
95                    && included_fields
96                        .iter()
97                        .any(|included| included == field_name)
98                {
99                    narrowed.push(path.clone());
100                }
101            }
102
103            // Nothing is requested below this `Select`, so prune the subtree rather than letting an
104            // opaque child re-request the whole scope.
105            if narrowed.is_empty() {
106                return Ok(FoldDownContext::Skip(()));
107            }
108            return Ok(FoldDownContext::Continue(narrowed));
109        }
110
111        // Any other function conservatively references each child's complete output.
112        Ok(FoldDownContext::Continue(vec![FieldPath::root()]))
113    }
114
115    fn visit_up(
116        &mut self,
117        _node: BoundExpression,
118        _requested: &Self::Context,
119        _children: Vec<()>,
120    ) -> VortexResult<FoldUp<()>> {
121        Ok(FoldUp::Continue(()))
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use vortex_array::dtype::DType;
128    use vortex_array::dtype::Nullability::NonNullable;
129    use vortex_array::dtype::PType::I32;
130    use vortex_array::dtype::StructFields;
131    use vortex_array::expr::Expression;
132    use vortex_array::expr::get_item;
133    use vortex_array::expr::pack;
134    use vortex_array::expr::root;
135    use vortex_array::expr::select;
136    use vortex_array::expr::select_exclude;
137    use vortex_utils::aliases::hash_set::HashSet;
138
139    use super::*;
140
141    fn scope() -> DType {
142        DType::Struct(
143            StructFields::from_iter([(
144                "a",
145                DType::Struct(
146                    StructFields::from_iter([("x", I32), ("y", I32)]),
147                    NonNullable,
148                ),
149            )]),
150            NonNullable,
151        )
152    }
153
154    /// Collects the prefix-minimal field paths referenced by `expr` against [`scope`].
155    fn referenced(expr: &Expression) -> VortexResult<HashSet<FieldPath>> {
156        Ok(referenced_field_paths(&expr.bind(&scope())?)?
157            .into_iter()
158            .collect())
159    }
160
161    #[test]
162    fn nested_select_preserves_field_path() -> VortexResult<()> {
163        let expr = select(["x"], get_item("a", root()));
164
165        assert_eq!(
166            referenced(&expr)?,
167            HashSet::from_iter([FieldPath::from_name("a").push("x")])
168        );
169        Ok(())
170    }
171
172    #[test]
173    fn get_item_after_select_only_references_requested_field() -> VortexResult<()> {
174        let expr = get_item("x", select(["x", "y"], get_item("a", root())));
175
176        assert_eq!(
177            referenced(&expr)?,
178            HashSet::from_iter([FieldPath::from_name("a").push("x")])
179        );
180        Ok(())
181    }
182
183    #[test]
184    fn select_exclude_references_included_fields() -> VortexResult<()> {
185        let expr = select_exclude(["y"], get_item("a", root()));
186
187        assert_eq!(
188            referenced(&expr)?,
189            HashSet::from_iter([FieldPath::from_name("a").push("x")])
190        );
191        Ok(())
192    }
193
194    #[test]
195    fn ancestor_path_subsumes_descendant() -> VortexResult<()> {
196        let expr = pack(
197            [
198                ("a", get_item("a", root())),
199                ("x", get_item("x", get_item("a", root()))),
200            ],
201            NonNullable,
202        );
203
204        assert_eq!(
205            referenced(&expr)?,
206            HashSet::from_iter([FieldPath::from_name("a")])
207        );
208        Ok(())
209    }
210
211    #[test]
212    fn get_item_through_opaque_fn_references_all_fields() -> VortexResult<()> {
213        // `pack` is opaque to the path analysis: a `GetItem` of its output must not be pushed down
214        // as a scope field access, so the wrapped `root()` conservatively references all fields.
215        let expr = get_item("x", pack([("x", root())], NonNullable));
216
217        assert_eq!(referenced(&expr)?, HashSet::from_iter([FieldPath::root()]));
218        Ok(())
219    }
220
221    #[test]
222    fn root_references_all_fields() -> VortexResult<()> {
223        assert_eq!(
224            referenced(&root())?,
225            HashSet::from_iter([FieldPath::root()])
226        );
227        Ok(())
228    }
229
230    #[test]
231    fn invalid_get_item_path_returns_error() {
232        let result = get_item("missing", root())
233            .bind(&scope())
234            .and_then(|expr| referenced_field_paths(&expr));
235        assert!(result.is_err());
236    }
237}