Skip to main content

vortex_scan/execution/
cache.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Plans, decoded values, and retained bytes shared by repeated scans of one input.
5
6use std::hash::Hash;
7use std::hash::Hasher;
8use std::sync::Arc;
9use std::sync::Weak;
10
11use parking_lot::Mutex;
12use rustc_hash::FxHashMap;
13use vortex_expr::BoundExpression;
14
15use super::io::SegmentRanges;
16use super::retain::RetainedSegments;
17use super::retain::RetainingSegmentSource;
18use crate::execution::FilterPlans;
19use crate::execution::pipeline::ValueCache;
20use crate::plan::PlanRef;
21use crate::source::SegmentSource;
22
23/// Reusable state for repeated scans of one source.
24///
25/// Every scan otherwise lowers the layout into a fresh physical plan, optimizes its projection
26/// over it, indexes every segment's byte range, and decodes the dictionary values it needs. A scan
27/// that finds an entry here reuses it, and one that misses builds the entry and keeps it for later
28/// scans. The lowered plan keeps the children it has initialized, each distinct projection keeps
29/// its optimized plan, each distinct filter keeps its conjunct and pruning plans along with the
30/// zones those plans have already excluded, and dictionary values stay keyed by the cached plan
31/// that produced them. Recently read segments are retained up to a byte budget, so the chunks of
32/// the file's scans that share a stored segment read it once.
33///
34/// A cache describes one root plan, segment locations, and segment source. Use a new cache
35/// when any of them changes. Cached plans and values live as long as the cache, one set per
36/// distinct projection.
37#[derive(Clone, Default)]
38pub struct ScanCache(Arc<Inner>);
39
40#[derive(Default)]
41struct Inner {
42    root: Mutex<Option<PlanRef>>,
43    /// Optimized plans of non-identity projections. Values are cached by the plan that produced
44    /// them, so a projection must reuse its plan for its values to be found again.
45    projections: Mutex<FxHashMap<ExprKey, PlanRef>>,
46    ranges: Mutex<Option<SegmentRanges>>,
47    /// Plans of filters, keyed by the filter expression. A pruning plan remembers the zones it
48    /// excluded, so sharing the plans prunes a file's zones once for every scan of that filter.
49    filters: Mutex<FxHashMap<ExprKey, Arc<FilterPlans>>>,
50    values: ValueCache,
51    /// Recently read segments, shared by the chunks of every scan of the file.
52    retained: Arc<RetainedSegments>,
53}
54
55impl ScanCache {
56    /// A cache whose scans retain up to `bytes` of recently read segments, so chunks that share
57    /// a stored segment read it once. The default retains 64 MiB; zero retains nothing.
58    pub fn with_retained_bytes(bytes: u64) -> Self {
59        Self(Arc::new(Inner {
60            retained: Arc::new(RetainedSegments::new(bytes)),
61            ..Inner::default()
62        }))
63    }
64
65    /// The lowered root plan an earlier scan kept.
66    pub(crate) fn root(&self) -> Option<PlanRef> {
67        self.0.root.lock().clone()
68    }
69
70    /// Keeps `root`, returning the plan already kept if another scan got there first.
71    pub(crate) fn insert_root(&self, root: PlanRef) -> PlanRef {
72        self.0.root.lock().get_or_insert(root).clone()
73    }
74
75    /// The optimized plan of `projection` an earlier scan kept.
76    pub(crate) fn projection(&self, projection: &BoundExpression) -> Option<PlanRef> {
77        self.0
78            .projections
79            .lock()
80            .get(&ExprKey(projection.clone()))
81            .cloned()
82    }
83
84    /// Keeps the optimized plan of `projection`, returning the plan already kept if another scan
85    /// got there first.
86    pub(crate) fn insert_projection(&self, projection: BoundExpression, plan: PlanRef) -> PlanRef {
87        self.0
88            .projections
89            .lock()
90            .entry(ExprKey(projection))
91            .or_insert(plan)
92            .clone()
93    }
94
95    /// The segment byte-range index an earlier scan kept.
96    pub(crate) fn ranges(&self) -> Option<SegmentRanges> {
97        self.0.ranges.lock().clone()
98    }
99
100    /// Keeps `ranges`, returning the index already kept if another scan got there first.
101    pub(crate) fn insert_ranges(&self, ranges: SegmentRanges) -> SegmentRanges {
102        Arc::clone(self.0.ranges.lock().get_or_insert(ranges))
103    }
104
105    /// The plans of `filter` an earlier scan kept.
106    pub(crate) fn filter_plans(&self, filter: &BoundExpression) -> Option<Arc<FilterPlans>> {
107        self.0.filters.lock().get(&ExprKey(filter.clone())).cloned()
108    }
109
110    /// Keeps the plans of `filter`, returning the plans already kept if another scan got there
111    /// first.
112    pub(crate) fn insert_filter_plans(
113        &self,
114        filter: BoundExpression,
115        plans: Arc<FilterPlans>,
116    ) -> Arc<FilterPlans> {
117        Arc::clone(
118            self.0
119                .filters
120                .lock()
121                .entry(ExprKey(filter))
122                .or_insert(plans),
123        )
124    }
125
126    /// Serves `segments` through the segments the file's scans retain.
127    pub(crate) fn retaining(&self, segments: Arc<dyn SegmentSource>) -> Arc<dyn SegmentSource> {
128        Arc::new(RetainingSegmentSource {
129            inner: segments,
130            retained: Arc::clone(&self.0.retained),
131        })
132    }
133
134    pub(crate) fn values(&self) -> ValueCache {
135        self.0.values.clone()
136    }
137
138    /// A handle that finds this cache while a scan holds it, without keeping it alive itself.
139    pub fn downgrade(&self) -> WeakScanCache {
140        WeakScanCache(Arc::downgrade(&self.0))
141    }
142}
143
144/// A bound expression keyed by structure, so equal expressions bound separately share an entry:
145/// an engine that opens a file once per partition binds its filter and projection once per
146/// partition.
147///
148/// Hashing skips dtypes, which equality still compares, so a lookup does not walk a wide schema.
149/// Both walk the tree iteratively, however deep it is.
150#[derive(Clone)]
151struct ExprKey(BoundExpression);
152
153impl PartialEq for ExprKey {
154    fn eq(&self, other: &Self) -> bool {
155        let mut pending = vec![(&self.0, &other.0)];
156        while let Some((lhs, rhs)) = pending.pop() {
157            if std::ptr::eq(lhs, rhs) {
158                continue;
159            }
160            if lhs.as_scalar() != rhs.as_scalar()
161                || lhs.children().len() != rhs.children().len()
162                || lhs.dtype() != rhs.dtype()
163            {
164                return false;
165            }
166            pending.extend(lhs.children().iter().zip(rhs.children()));
167        }
168        true
169    }
170}
171
172impl Eq for ExprKey {}
173
174impl Hash for ExprKey {
175    fn hash<H: Hasher>(&self, state: &mut H) {
176        let mut pending = vec![&self.0];
177        while let Some(expr) = pending.pop() {
178            expr.as_scalar().hash(state);
179            expr.children().len().hash(state);
180            pending.extend(expr.children());
181        }
182    }
183}
184
185/// A [`ScanCache`] handle that does not keep the cache alive. Engines that open a file once per
186/// partition keep one per file, so concurrent partitions share a cache that is freed with the
187/// last scan holding it.
188#[derive(Clone)]
189pub struct WeakScanCache(Weak<Inner>);
190
191impl WeakScanCache {
192    /// The cache, while a scan still holds it.
193    pub fn upgrade(&self) -> Option<ScanCache> {
194        self.0.upgrade().map(ScanCache)
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use std::hash::BuildHasher;
201
202    use rstest::rstest;
203    use vortex_array::dtype::DType;
204    use vortex_array::dtype::Nullability;
205    use vortex_array::dtype::PType;
206    use vortex_error::VortexResult;
207    use vortex_expr::Expression;
208    use vortex_expr::get_item;
209    use vortex_expr::gt;
210    use vortex_expr::lit;
211    use vortex_expr::lt;
212    use vortex_expr::root;
213
214    use super::ExprKey;
215
216    fn ints_gt(value: i32) -> Expression {
217        gt(get_item("ints", root()), lit(value))
218    }
219
220    fn table(ints: PType) -> DType {
221        DType::struct_(
222            [("ints", DType::Primitive(ints, Nullability::NonNullable))],
223            Nullability::NonNullable,
224        )
225    }
226
227    #[test]
228    fn separately_bound_equal_expressions_share_a_key() -> VortexResult<()> {
229        let dtype = table(PType::I32);
230        let lhs = ExprKey(ints_gt(5).bind(&dtype)?);
231        let rhs = ExprKey(ints_gt(5).bind(&dtype)?);
232        assert!(lhs == rhs);
233        assert_eq!(
234            rustc_hash::FxBuildHasher.hash_one(&lhs),
235            rustc_hash::FxBuildHasher.hash_one(&rhs)
236        );
237        Ok(())
238    }
239
240    #[rstest]
241    #[case::literal(ints_gt(6), table(PType::I32))]
242    #[case::function(lt(get_item("ints", root()), lit(5i32)), table(PType::I32))]
243    #[case::dtype(get_item("ints", root()), table(PType::I64))]
244    fn different_expressions_have_different_keys(
245        #[case] other: Expression,
246        #[case] dtype: DType,
247    ) -> VortexResult<()> {
248        let i32s = table(PType::I32);
249        for key in [ints_gt(5), get_item("ints", root())] {
250            assert!(ExprKey(key.bind(&i32s)?) != ExprKey(other.bind(&dtype)?));
251        }
252        Ok(())
253    }
254}