Skip to main content

hawdb_cascades/
properties.rs

1// Copyright 2026 Nowledge
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
15#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
16pub struct RequiredProperties {
17    pub distribution: Distribution,
18    pub ordering: Vec<String>,
19    pub covering_fields: Vec<String>,
20    pub requires_scan_pruning: bool,
21    pub requires_raw_vector_rerank: bool,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
25pub struct PhysicalProperties {
26    pub distribution: Distribution,
27    pub ordering: Vec<String>,
28    pub covering_fields: Vec<String>,
29    pub scan_pruning: ScanPruningSupport,
30    pub vector_precision: VectorPrecision,
31    pub memory_budget: MemoryBudgetClass,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
35pub enum Distribution {
36    #[default]
37    Any,
38    Single,
39    Hash(Vec<String>),
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
43pub enum ScanPruningSupport {
44    #[default]
45    Unknown,
46    None,
47    Label,
48    Segment,
49    Index,
50    ExactEmpty,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
54pub enum VectorPrecision {
55    #[default]
56    NotVector,
57    ApproximateCandidate,
58    RawReranked,
59    Exact,
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
63pub enum MemoryBudgetClass {
64    #[default]
65    Unknown,
66    Constant,
67    RowLinear,
68    Blocking,
69}
70
71impl PhysicalProperties {
72    /// Requested owned heap. Keep the framework independent of value/core data.
73    #[doc(hidden)]
74    pub fn retained_heap_bytes(&self) -> Option<usize> {
75        let Self {
76            distribution,
77            ordering,
78            covering_fields,
79            scan_pruning,
80            vector_precision,
81            memory_budget,
82        } = self;
83        fn strings(values: &Vec<String>) -> Option<usize> {
84            values.iter().try_fold(
85                values
86                    .capacity()
87                    .checked_mul(std::mem::size_of::<String>())?,
88                |bytes, value| bytes.checked_add(value.capacity()),
89            )
90        }
91        fn leaf<T: Copy>(_: &T) {}
92        leaf(scan_pruning);
93        leaf(vector_precision);
94        leaf(memory_budget);
95        let distribution = match distribution {
96            Distribution::Any | Distribution::Single => 0,
97            Distribution::Hash(keys) => strings(keys)?,
98        };
99        distribution
100            .checked_add(strings(ordering)?)?
101            .checked_add(strings(covering_fields)?)
102    }
103
104    pub fn satisfies(&self, required: &RequiredProperties) -> bool {
105        distribution_satisfies(&self.distribution, &required.distribution)
106            && ordering_satisfies(&self.ordering, &required.ordering)
107            && covering_satisfies(&self.covering_fields, &required.covering_fields)
108            && scan_pruning_satisfies(self.scan_pruning, required.requires_scan_pruning)
109            && vector_rerank_satisfies(self.vector_precision, required.requires_raw_vector_rerank)
110    }
111}
112
113impl Distribution {
114    pub fn as_str(&self) -> &'static str {
115        match self {
116            Distribution::Any => "any",
117            Distribution::Single => "single",
118            Distribution::Hash(_) => "hash",
119        }
120    }
121}
122
123impl ScanPruningSupport {
124    pub fn as_str(self) -> &'static str {
125        match self {
126            ScanPruningSupport::Unknown => "unknown",
127            ScanPruningSupport::None => "none",
128            ScanPruningSupport::Label => "label",
129            ScanPruningSupport::Segment => "segment",
130            ScanPruningSupport::Index => "index",
131            ScanPruningSupport::ExactEmpty => "exact_empty",
132        }
133    }
134
135    pub fn is_prunable(self) -> bool {
136        matches!(
137            self,
138            ScanPruningSupport::Label
139                | ScanPruningSupport::Segment
140                | ScanPruningSupport::Index
141                | ScanPruningSupport::ExactEmpty
142        )
143    }
144}
145
146impl VectorPrecision {
147    pub fn as_str(self) -> &'static str {
148        match self {
149            VectorPrecision::NotVector => "not_vector",
150            VectorPrecision::ApproximateCandidate => "approximate_candidate",
151            VectorPrecision::RawReranked => "raw_reranked",
152            VectorPrecision::Exact => "exact",
153        }
154    }
155
156    pub fn includes_raw_rerank(self) -> bool {
157        matches!(self, VectorPrecision::RawReranked | VectorPrecision::Exact)
158    }
159}
160
161impl MemoryBudgetClass {
162    pub fn as_str(self) -> &'static str {
163        match self {
164            MemoryBudgetClass::Unknown => "unknown",
165            MemoryBudgetClass::Constant => "constant",
166            MemoryBudgetClass::RowLinear => "row_linear",
167            MemoryBudgetClass::Blocking => "blocking",
168        }
169    }
170}
171
172fn distribution_satisfies(actual: &Distribution, required: &Distribution) -> bool {
173    match required {
174        Distribution::Any => true,
175        Distribution::Single => actual == required,
176        Distribution::Hash(keys) => {
177            matches!(actual, Distribution::Hash(actual_keys) if actual_keys == keys)
178        }
179    }
180}
181
182fn covering_satisfies(actual: &[String], required: &[String]) -> bool {
183    required.iter().all(|field| actual.contains(field))
184}
185
186fn scan_pruning_satisfies(actual: ScanPruningSupport, required: bool) -> bool {
187    !required || actual.is_prunable()
188}
189
190fn vector_rerank_satisfies(actual: VectorPrecision, required: bool) -> bool {
191    !required || actual.includes_raw_rerank()
192}
193
194fn ordering_satisfies(actual: &[String], required: &[String]) -> bool {
195    required.is_empty()
196        || (actual.len() >= required.len()
197            && actual
198                .iter()
199                .zip(required.iter())
200                .all(|(actual, required)| actual == required))
201}
202
203#[cfg(test)]
204mod tests {
205    use super::{
206        Distribution, MemoryBudgetClass, PhysicalProperties, RequiredProperties,
207        ScanPruningSupport, VectorPrecision,
208    };
209
210    #[test]
211    fn empty_required_properties_accept_any_plan() {
212        let actual = PhysicalProperties {
213            distribution: Distribution::Hash(vec!["space_id".to_string()]),
214            ordering: vec!["updated_at".to_string()],
215            scan_pruning: ScanPruningSupport::Index,
216            ..PhysicalProperties::default()
217        };
218
219        assert!(actual.satisfies(&RequiredProperties::default()));
220    }
221
222    #[test]
223    fn ordering_requirement_accepts_prefix_match() {
224        let actual = PhysicalProperties {
225            distribution: Distribution::Single,
226            ordering: vec!["space_id".to_string(), "updated_at".to_string()],
227            ..PhysicalProperties::default()
228        };
229        let required = RequiredProperties {
230            distribution: Distribution::Single,
231            ordering: vec!["space_id".to_string()],
232            ..RequiredProperties::default()
233        };
234
235        assert!(actual.satisfies(&required));
236    }
237
238    #[test]
239    fn embedded_requirements_check_covering_pruning_and_vector_rerank() {
240        let actual = PhysicalProperties {
241            distribution: Distribution::Single,
242            covering_fields: vec!["Memory.id".to_string(), "Memory.title".to_string()],
243            scan_pruning: ScanPruningSupport::Index,
244            vector_precision: VectorPrecision::RawReranked,
245            memory_budget: MemoryBudgetClass::RowLinear,
246            ..PhysicalProperties::default()
247        };
248
249        assert!(actual.satisfies(&RequiredProperties {
250            distribution: Distribution::Single,
251            covering_fields: vec!["Memory.id".to_string()],
252            requires_scan_pruning: true,
253            requires_raw_vector_rerank: true,
254            ..RequiredProperties::default()
255        }));
256        assert!(!actual.satisfies(&RequiredProperties {
257            covering_fields: vec!["Memory.embedding".to_string()],
258            ..RequiredProperties::default()
259        }));
260        assert!(
261            !PhysicalProperties::default().satisfies(&RequiredProperties {
262                requires_scan_pruning: true,
263                ..RequiredProperties::default()
264            })
265        );
266    }
267
268    #[test]
269    fn distribution_exposes_stable_names() {
270        assert_eq!(Distribution::Any.as_str(), "any");
271        assert_eq!(Distribution::Single.as_str(), "single");
272        assert_eq!(
273            Distribution::Hash(vec!["space_id".to_string()]).as_str(),
274            "hash"
275        );
276        assert_eq!(ScanPruningSupport::Index.as_str(), "index");
277        assert_eq!(ScanPruningSupport::Segment.as_str(), "segment");
278        assert_eq!(VectorPrecision::RawReranked.as_str(), "raw_reranked");
279        assert_eq!(MemoryBudgetClass::Blocking.as_str(), "blocking");
280    }
281}