Skip to main content

hawdb_optimizer_graph/graph/catalog/
distribution.rs

1// Copyright 2026 Nowledge
2// SPDX-License-Identifier: Apache-2.0
3
4//! One distribution estimate feeds access ranking, residual selectivity and
5//! final costing. Exact query-local point counts retain precedence.
6
7use super::*;
8use hawdb_core::{CompressedHistogram, PropertyCardinalityEstimate};
9
10impl OptimizerCatalog {
11    pub fn with_statistics_parameter_values(mut self, values: BTreeMap<Value, Value>) -> Self {
12        self.statistics_parameter_values = values;
13        self
14    }
15
16    pub(in crate::graph) fn statistics_value<'a>(&'a self, value: &'a Value) -> &'a Value {
17        self.statistics_parameter_values.get(value).unwrap_or(value)
18    }
19
20    pub(in crate::graph) fn property_distribution(
21        &self,
22        label: &str,
23        property: &str,
24    ) -> Option<&CompressedHistogram> {
25        self.property_distributions
26            .get(&(label.to_owned(), property.to_owned()))
27    }
28
29    pub(in crate::graph) fn rel_property_distribution(
30        &self,
31        rel_type: &str,
32        property: &str,
33    ) -> Option<&CompressedHistogram> {
34        self.rel_property_distributions
35            .get(&(rel_type.to_owned(), property.to_owned()))
36    }
37
38    pub(in crate::graph) fn property_equality_estimate(
39        &self,
40        label: &str,
41        property: &str,
42        value: &Value,
43        input_rows: u64,
44    ) -> Option<PropertyCardinalityEstimate> {
45        if self.query_local_property_eq_rows(label, property).is_some() {
46            return None;
47        }
48        let histogram = self.property_distribution(label, property)?;
49        let value = self.statistics_value(value);
50        compatible(histogram, value).then(|| {
51            histogram.equality(
52                value,
53                input_rows,
54                self.known_distinct_count(label, property),
55            )
56        })
57    }
58
59    pub(in crate::graph) fn estimate_property_value_rows(
60        &self,
61        label: &str,
62        property: &str,
63        value: &Value,
64        input_rows: u64,
65    ) -> u64 {
66        self.property_equality_estimate(label, property, value, input_rows)
67            .map_or_else(
68                || self.estimate_property_eq_rows(label, property, input_rows),
69                |estimate| estimate.rows.max(1),
70            )
71    }
72
73    pub(in crate::graph) fn estimate_property_index_value_rows(
74        &self,
75        label: &str,
76        property: &str,
77        value: &Value,
78    ) -> u64 {
79        self.property_equality_estimate(label, property, value, self.label_count(label))
80            .map_or_else(
81                || self.estimate_property_index_eq_rows(label, property),
82                |estimate| estimate.rows.max(1),
83            )
84    }
85
86    pub(in crate::graph) fn estimate_property_index_values_rows(
87        &self,
88        label: &str,
89        property: &str,
90        values: &[Value],
91    ) -> u64 {
92        self.distribution_in_rows(label, property, values, self.label_count(label))
93            .unwrap_or_else(|| {
94                self.estimate_property_index_in_rows(label, property, values.len() as u64)
95            })
96    }
97
98    pub(in crate::graph) fn distribution_in_rows(
99        &self,
100        label: &str,
101        property: &str,
102        values: &[Value],
103        input_rows: u64,
104    ) -> Option<u64> {
105        let mut seen = BTreeSet::new();
106        let mut rows = 0_u64;
107        for value in values {
108            let value = self.statistics_value(value);
109            if !seen.insert(value) {
110                continue;
111            }
112            rows = rows.saturating_add(
113                self.property_equality_estimate(label, property, value, input_rows)?
114                    .rows,
115            );
116        }
117        Some(rows.min(input_rows).max(1))
118    }
119
120    pub(in crate::graph) fn rel_property_equality_estimate(
121        &self,
122        rel_type: &str,
123        property: &str,
124        value: &Value,
125        input_rows: u64,
126    ) -> Option<PropertyCardinalityEstimate> {
127        let histogram = self.rel_property_distribution(rel_type, property)?;
128        let value = self.statistics_value(value);
129        compatible(histogram, value).then(|| {
130            histogram.equality(
131                value,
132                input_rows,
133                self.known_rel_property_distinct_count(rel_type, property),
134            )
135        })
136    }
137
138    pub(in crate::graph) fn estimate_rel_property_value_rows(
139        &self,
140        rel_type: &str,
141        property: &str,
142        value: &Value,
143        input_rows: u64,
144    ) -> u64 {
145        self.rel_property_equality_estimate(rel_type, property, value, input_rows)
146            .map_or_else(
147                || self.estimate_rel_property_eq_rows(rel_type, property, input_rows),
148                |estimate| estimate.rows.max(1),
149            )
150    }
151
152    pub(in crate::graph) fn estimate_property_not_value_rows(
153        &self,
154        label: &str,
155        property: &str,
156        value: &Value,
157        input_rows: u64,
158    ) -> u64 {
159        if matches!(self.statistics_value(value), Value::Null) {
160            return 1;
161        }
162        self.property_equality_estimate(label, property, value, input_rows)
163            .map_or_else(
164                || self.estimate_property_not_eq_rows(label, property, input_rows),
165                |estimate| {
166                    input_rows
167                        .saturating_sub(
168                            self.property_distribution(label, property)
169                                .unwrap()
170                                .nulls(input_rows)
171                                .rows,
172                        )
173                        .saturating_sub(estimate.rows)
174                        .max(1)
175                },
176            )
177    }
178
179    pub(in crate::graph) fn estimate_rel_property_not_value_rows(
180        &self,
181        rel_type: &str,
182        property: &str,
183        value: &Value,
184        input_rows: u64,
185    ) -> u64 {
186        let value = self.statistics_value(value);
187        if matches!(value, Value::Null) {
188            return 1;
189        }
190        let Some(histogram) = self
191            .rel_property_distribution(rel_type, property)
192            .filter(|histogram| compatible(histogram, value))
193        else {
194            return self.estimate_rel_property_not_eq_rows(rel_type, property, input_rows);
195        };
196        input_rows
197            .saturating_sub(histogram.nulls(input_rows).rows)
198            .saturating_sub(
199                self.estimate_rel_property_value_rows(rel_type, property, value, input_rows),
200            )
201            .max(1)
202    }
203
204    pub(in crate::graph) fn distribution_comparison_rows(
205        &self,
206        label: &str,
207        property: &str,
208        op: ComparisonOp,
209        value: &Value,
210        input_rows: u64,
211        relationship: bool,
212    ) -> Option<u64> {
213        let (lower, upper) = match op {
214            ComparisonOp::Lt => (None, Some((value, false))),
215            ComparisonOp::Lte => (None, Some((value, true))),
216            ComparisonOp::Gt => (Some((value, false)), None),
217            ComparisonOp::Gte => (Some((value, true)), None),
218        };
219        self.distribution_range_rows(label, property, lower, upper, input_rows, relationship)
220    }
221
222    pub(in crate::graph) fn distribution_range_rows(
223        &self,
224        label: &str,
225        property: &str,
226        lower: Option<(&Value, bool)>,
227        upper: Option<(&Value, bool)>,
228        input_rows: u64,
229        relationship: bool,
230    ) -> Option<u64> {
231        let histogram = if relationship {
232            self.rel_property_distribution(label, property)?
233        } else {
234            self.property_distribution(label, property)?
235        };
236        let lower = lower.map(|(value, inclusive)| (self.statistics_value(value), inclusive));
237        let upper = upper.map(|(value, inclusive)| (self.statistics_value(value), inclusive));
238        for value in lower.into_iter().chain(upper).map(|(value, _)| value) {
239            if !matches!(
240                value,
241                Value::Int(_)
242                    | Value::Float(_)
243                    | Value::String(_)
244                    | Value::Date(_)
245                    | Value::LocalTime(_)
246                    | Value::LocalDateTime(_)
247                    | Value::DateTime(_)
248            ) || !compatible(histogram, value)
249            {
250                return None;
251            }
252        }
253        Some(histogram.range(lower, upper, input_rows).rows.max(1))
254    }
255}
256
257pub(super) fn compatible(histogram: &CompressedHistogram, value: &Value) -> bool {
258    matches!(value, Value::Null)
259        || histogram
260            .most_common
261            .iter()
262            .map(|entry| &entry.value)
263            .chain(
264                histogram
265                    .buckets
266                    .iter()
267                    .flat_map(|bucket| [&bucket.lower, &bucket.upper]),
268            )
269            .all(|sample| std::mem::discriminant(sample) == std::mem::discriminant(value))
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn query_overrides_share_statistics_and_fixture_mutation_forks_the_snapshot() {
278        let mut catalog = OptimizerCatalog::default();
279        catalog.label_counts.insert("Memory".into(), 100);
280        catalog.property_histograms.insert(
281            ("Memory".into(), "space".into()),
282            vec![Value::String("x".repeat(8192))],
283        );
284        let mut query = catalog
285            .clone()
286            .with_statistics_parameter_values(BTreeMap::new())
287            .with_property_equality_row_count("Memory".into(), "space".into(), 2);
288        assert!(std::sync::Arc::ptr_eq(
289            &catalog.statistics,
290            &query.statistics
291        ));
292        assert_eq!(
293            catalog
294                .property_histograms
295                .values()
296                .next()
297                .unwrap()
298                .as_ptr(),
299            query.property_histograms.values().next().unwrap().as_ptr()
300        );
301        query.label_counts.insert("Memory".into(), 200);
302        assert_eq!(catalog.label_count("Memory"), 100);
303        assert_eq!(query.label_count("Memory"), 200);
304        assert!(!std::sync::Arc::ptr_eq(
305            &catalog.statistics,
306            &query.statistics
307        ));
308    }
309
310    #[test]
311    fn shared_distribution_handles_skew_nulls_and_point_override() {
312        let histogram = CompressedHistogram::from_sample(
313            100,
314            80,
315            5,
316            15,
317            std::iter::repeat_n(Value::String("hot".into()), 70)
318                .chain(std::iter::repeat_n(Value::String("cold".into()), 10))
319                .collect(),
320        )
321        .unwrap();
322        let catalog = OptimizerCatalog::new(
323            OptimizerCatalogIndexes::default(),
324            OptimizerCatalogStatistics {
325                label_counts: BTreeMap::from([("Memory".into(), 100)]),
326                ..OptimizerCatalogStatistics::default()
327            }
328            .with_distributions(
329                [(("Memory".into(), "space".into()), histogram.clone())],
330                [(("LINK".into(), "space".into()), histogram)],
331            ),
332        );
333        let hot = Value::String("hot".into());
334        let cold = Value::String("cold".into());
335        assert_eq!(
336            catalog.estimate_property_value_rows("Memory", "space", &hot, 100),
337            70
338        );
339        assert_eq!(
340            catalog.estimate_property_index_value_rows("Memory", "space", &cold),
341            10
342        );
343        assert_eq!(
344            catalog.distribution_in_rows(
345                "Memory",
346                "space",
347                &[cold.clone(), cold.clone(), Value::Null],
348                100
349            ),
350            Some(10)
351        );
352        assert_eq!(
353            catalog.estimate_property_not_value_rows("Memory", "space", &hot, 100),
354            10
355        );
356        assert_eq!(
357            catalog.estimate_property_not_value_rows("Memory", "space", &Value::Null, 100),
358            1
359        );
360        assert_eq!(
361            catalog.estimate_rel_property_value_rows("LINK", "space", &hot, 100),
362            70
363        );
364        assert_eq!(
365            catalog.estimate_rel_property_not_value_rows("LINK", "space", &hot, 100),
366            10
367        );
368        assert_eq!(
369            catalog.estimate_rel_property_in_rows("LINK", "space", &[cold.clone(), cold], 100),
370            10
371        );
372        let local = catalog.with_property_equality_row_count("Memory".into(), "space".into(), 3);
373        assert_eq!(
374            local.estimate_property_index_value_rows("Memory", "space", &hot),
375            3
376        );
377    }
378}