Skip to main content

hawdb_optimizer_graph/graph/
catalog.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
15use super::value_range::{compare_histogram_value, range_bound_matches, ValueRangeBound};
16use crate::cardinality_defaults::{
17    NULL_SELECTIVITY_DIVISOR_CAP, RANGE_SELECTIVITY_DIVISOR, SAMPLED_HISTOGRAM_MATCH_PSEUDOCOUNT,
18    SAMPLED_HISTOGRAM_TOTAL_PSEUDOCOUNT,
19};
20use hawdb_core::{Catalog, GraphStatistics, IndexKind, Value};
21use hawdb_plan_cypher::ComparisonOp;
22use std::collections::{BTreeMap, BTreeSet};
23
24mod joint;
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub(super) struct ExpandEstimate {
28    pub(super) path_count: Option<u64>,
29    pub(super) rel_count: u64,
30    pub(super) source_count: u64,
31    pub(super) average_fanout: u64,
32    pub(super) property_distinct_product: u64,
33    pub(super) estimated_rows: u64,
34    pub(super) hop_estimates: Vec<HopEstimate>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub(super) struct HopEstimate {
39    pub(super) hop: usize,
40    pub(super) rows: u64,
41    pub(super) exact: bool,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct OptimizerIndexStatistics {
46    pub index_size: u64,
47    pub distinct_count: u64,
48}
49
50#[derive(Debug, Default, Clone, PartialEq, Eq)]
51pub struct OptimizerCatalog {
52    // Catalog containers are COW snapshots. Keep the source identity without
53    // copying descriptor maps or collecting values from the graph at planning time.
54    pub(super) source_schema: Option<Catalog>,
55    pub(super) parameter_scalar_types: BTreeMap<Value, hawdb_core::PropertyType>,
56    pub(super) assume_all_indexes: bool,
57    pub(super) equality_property_indexes: BTreeSet<(String, String)>,
58    pub(super) composite_property_indexes: BTreeSet<(String, Vec<String>)>,
59    pub(super) range_property_indexes: BTreeSet<(String, String)>,
60    pub(super) ordered_range_indexes: BTreeSet<(String, String)>,
61    pub(super) ordered_composite_indexes:
62        BTreeMap<(String, Vec<String>), Vec<hawdb_core::PropertyType>>,
63    pub(super) full_text_property_indexes: BTreeSet<(String, String)>,
64    pub(super) label_counts: BTreeMap<String, u64>,
65    pub(super) rel_type_counts: BTreeMap<String, u64>,
66    pub(super) rel_type_source_counts: BTreeMap<String, u64>,
67    pub(super) rel_type_target_counts: BTreeMap<String, u64>,
68    pub(super) path_counts: BTreeMap<(String, String, String), u64>,
69    pub(super) path_source_distinct_counts: BTreeMap<(String, String, String), u64>,
70    pub(super) path_target_distinct_counts: BTreeMap<(String, String, String), u64>,
71    pub(super) bounded_path_counts: BTreeMap<(String, String, String, usize), u64>,
72    pub(super) bounded_path_source_distinct_counts: BTreeMap<(String, String, String, usize), u64>,
73    pub(super) bounded_path_target_distinct_counts: BTreeMap<(String, String, String, usize), u64>,
74    pub(super) property_index_statistics: BTreeMap<(String, String), OptimizerIndexStatistics>,
75    property_equality_row_count: Option<((String, String), u64)>,
76    pub(super) composite_index_statistics:
77        BTreeMap<(String, Vec<String>), OptimizerIndexStatistics>,
78    joint_statistics: BTreeMap<(String, Vec<String>), Option<OptimizerIndexStatistics>>,
79    pub(super) property_distinct_counts: BTreeMap<(String, String), u64>,
80    pub(super) rel_property_distinct_counts: BTreeMap<(String, String), u64>,
81    pub(super) property_histograms: BTreeMap<(String, String), Vec<Value>>,
82    pub(super) rel_property_histograms: BTreeMap<(String, String), Vec<Value>>,
83    pub(super) sampled_property_histograms: BTreeMap<(String, String), bool>,
84    pub(super) sampled_rel_property_histograms: BTreeMap<(String, String), bool>,
85}
86
87#[derive(Debug, Default, Clone, PartialEq, Eq)]
88pub struct OptimizerCatalogIndexes {
89    pub(super) equality_property_indexes: BTreeSet<(String, String)>,
90    pub(super) composite_property_indexes: BTreeSet<(String, Vec<String>)>,
91    pub(super) range_property_indexes: BTreeSet<(String, String)>,
92    pub(super) full_text_property_indexes: BTreeSet<(String, String)>,
93}
94
95#[derive(Debug, Default, Clone, PartialEq, Eq)]
96pub struct OptimizerCatalogStatistics {
97    pub(super) label_counts: BTreeMap<String, u64>,
98    pub(super) rel_type_counts: BTreeMap<String, u64>,
99    pub(super) rel_type_source_counts: BTreeMap<String, u64>,
100    pub(super) rel_type_target_counts: BTreeMap<String, u64>,
101    pub(super) path_counts: BTreeMap<(String, String, String), u64>,
102    pub(super) path_source_distinct_counts: BTreeMap<(String, String, String), u64>,
103    pub(super) path_target_distinct_counts: BTreeMap<(String, String, String), u64>,
104    pub(super) bounded_path_counts: BTreeMap<(String, String, String, usize), u64>,
105    pub(super) bounded_path_source_distinct_counts: BTreeMap<(String, String, String, usize), u64>,
106    pub(super) bounded_path_target_distinct_counts: BTreeMap<(String, String, String, usize), u64>,
107    pub(super) property_index_statistics: BTreeMap<(String, String), OptimizerIndexStatistics>,
108    pub(super) composite_index_statistics:
109        BTreeMap<(String, Vec<String>), OptimizerIndexStatistics>,
110    pub(super) property_distinct_counts: BTreeMap<(String, String), u64>,
111    pub(super) rel_property_distinct_counts: BTreeMap<(String, String), u64>,
112    pub(super) property_histograms: BTreeMap<(String, String), Vec<Value>>,
113    pub(super) rel_property_histograms: BTreeMap<(String, String), Vec<Value>>,
114    pub(super) sampled_property_histograms: BTreeMap<(String, String), bool>,
115    pub(super) sampled_rel_property_histograms: BTreeMap<(String, String), bool>,
116}
117
118/// Converts storage-neutral schema and statistics into optimizer cost inputs.
119///
120/// Basic cardinalities remain usable while an advanced statistics refresh is
121/// incomplete; only advanced histograms, path counts, and index samples are
122/// withheld in that state.
123#[doc(hidden)]
124pub fn optimizer_catalog_from_graph_statistics(
125    catalog: &Catalog,
126    statistics: &GraphStatistics,
127) -> OptimizerCatalog {
128    let advanced_statistics = statistics
129        .advanced_statistics_complete
130        .then_some(statistics);
131    let equality_property_indexes = catalog.property_indexes().filter_map(|index| {
132        if index.kind != IndexKind::Equality {
133            return None;
134        }
135        catalog
136            .label_name(index.label_id)
137            .map(|label| (label.to_string(), index.property.clone()))
138    });
139    let composite_property_indexes = catalog.composite_property_indexes().filter_map(|index| {
140        catalog
141            .label_name(index.label_id)
142            .map(|label| (label.to_string(), index.properties.clone()))
143    });
144    let range_property_indexes = catalog.property_indexes().filter_map(|index| {
145        if index.kind != IndexKind::Range {
146            return None;
147        }
148        catalog
149            .label_name(index.label_id)
150            .map(|label| (label.to_string(), index.property.clone()))
151    });
152    let full_text_property_indexes = catalog.property_indexes().filter_map(|index| {
153        if index.kind != IndexKind::FullText {
154            return None;
155        }
156        catalog
157            .label_name(index.label_id)
158            .map(|label| (label.to_string(), index.property.clone()))
159    });
160    let label_counts = statistics
161        .label_counts
162        .iter()
163        .filter_map(|(label_id, count)| {
164            catalog
165                .label_name(*label_id)
166                .map(|label| (label.to_string(), *count))
167        });
168    let rel_type_counts = statistics
169        .rel_type_counts
170        .iter()
171        .filter_map(|(rel_type_id, count)| {
172            catalog
173                .rel_type_name(*rel_type_id)
174                .map(|rel_type| (rel_type.to_string(), *count))
175        });
176    let rel_type_source_counts = advanced_statistics
177        .into_iter()
178        .flat_map(|statistics| statistics.rel_type_source_counts.iter())
179        .filter_map(|(rel_type_id, count)| {
180            catalog
181                .rel_type_name(*rel_type_id)
182                .map(|rel_type| (rel_type.to_string(), *count))
183        });
184    let rel_type_target_counts = advanced_statistics
185        .into_iter()
186        .flat_map(|statistics| statistics.rel_type_target_counts.iter())
187        .filter_map(|(rel_type_id, count)| {
188            catalog
189                .rel_type_name(*rel_type_id)
190                .map(|rel_type| (rel_type.to_string(), *count))
191        });
192    let path_counts = advanced_statistics
193        .into_iter()
194        .flat_map(|statistics| statistics.path_counts.iter())
195        .filter_map(|((source_label_id, rel_type_id, target_label_id), count)| {
196            Some((
197                (
198                    catalog.label_name(*source_label_id)?.to_string(),
199                    catalog.rel_type_name(*rel_type_id)?.to_string(),
200                    catalog.label_name(*target_label_id)?.to_string(),
201                ),
202                *count,
203            ))
204        });
205    let path_source_distinct_counts = advanced_statistics
206        .into_iter()
207        .flat_map(|statistics| statistics.path_source_distinct_counts.iter())
208        .filter_map(|((source_label_id, rel_type_id, target_label_id), count)| {
209            Some((
210                (
211                    catalog.label_name(*source_label_id)?.to_string(),
212                    catalog.rel_type_name(*rel_type_id)?.to_string(),
213                    catalog.label_name(*target_label_id)?.to_string(),
214                ),
215                *count,
216            ))
217        });
218    let path_target_distinct_counts = advanced_statistics
219        .into_iter()
220        .flat_map(|statistics| statistics.path_target_distinct_counts.iter())
221        .filter_map(|((source_label_id, rel_type_id, target_label_id), count)| {
222            Some((
223                (
224                    catalog.label_name(*source_label_id)?.to_string(),
225                    catalog.rel_type_name(*rel_type_id)?.to_string(),
226                    catalog.label_name(*target_label_id)?.to_string(),
227                ),
228                *count,
229            ))
230        });
231    let bounded_path_counts = advanced_statistics
232        .into_iter()
233        .flat_map(|statistics| statistics.bounded_path_counts.iter())
234        .filter_map(
235            |((source_label_id, rel_type_id, target_label_id, hops), count)| {
236                Some((
237                    (
238                        catalog.label_name(*source_label_id)?.to_string(),
239                        catalog.rel_type_name(*rel_type_id)?.to_string(),
240                        catalog.label_name(*target_label_id)?.to_string(),
241                        *hops,
242                    ),
243                    *count,
244                ))
245            },
246        );
247    let bounded_path_source_distinct_counts = advanced_statistics
248        .into_iter()
249        .flat_map(|statistics| statistics.bounded_path_source_distinct_counts.iter())
250        .filter_map(
251            |((source_label_id, rel_type_id, target_label_id, hops), count)| {
252                Some((
253                    (
254                        catalog.label_name(*source_label_id)?.to_string(),
255                        catalog.rel_type_name(*rel_type_id)?.to_string(),
256                        catalog.label_name(*target_label_id)?.to_string(),
257                        *hops,
258                    ),
259                    *count,
260                ))
261            },
262        );
263    let bounded_path_target_distinct_counts = advanced_statistics
264        .into_iter()
265        .flat_map(|statistics| statistics.bounded_path_target_distinct_counts.iter())
266        .filter_map(
267            |((source_label_id, rel_type_id, target_label_id, hops), count)| {
268                Some((
269                    (
270                        catalog.label_name(*source_label_id)?.to_string(),
271                        catalog.rel_type_name(*rel_type_id)?.to_string(),
272                        catalog.label_name(*target_label_id)?.to_string(),
273                        *hops,
274                    ),
275                    *count,
276                ))
277            },
278        );
279    let property_distinct_counts = advanced_statistics
280        .into_iter()
281        .flat_map(|statistics| statistics.property_distinct_counts.iter())
282        .filter_map(|((label_id, property), count)| {
283            catalog
284                .label_name(*label_id)
285                .map(|label| ((label.to_string(), property.clone()), *count))
286        });
287    let property_histograms = advanced_statistics
288        .into_iter()
289        .flat_map(|statistics| statistics.property_histograms.iter())
290        .filter_map(|((label_id, property), values)| {
291            catalog
292                .label_name(*label_id)
293                .map(|label| ((label.to_string(), property.clone()), values.clone()))
294        });
295    let sampled_property_histograms = advanced_statistics
296        .into_iter()
297        .flat_map(|statistics| statistics.sampled_property_histograms.iter())
298        .filter_map(|((label_id, property), sampled)| {
299            catalog
300                .label_name(*label_id)
301                .map(|label| ((label.to_string(), property.clone()), *sampled))
302        });
303    let rel_property_distinct_counts = advanced_statistics
304        .into_iter()
305        .flat_map(|statistics| statistics.rel_property_distinct_counts.iter())
306        .filter_map(|((rel_type_id, property), count)| {
307            catalog
308                .rel_type_name(*rel_type_id)
309                .map(|rel_type| ((rel_type.to_string(), property.clone()), *count))
310        });
311    let rel_property_histograms = advanced_statistics
312        .into_iter()
313        .flat_map(|statistics| statistics.rel_property_histograms.iter())
314        .filter_map(|((rel_type_id, property), values)| {
315            catalog
316                .rel_type_name(*rel_type_id)
317                .map(|rel_type| ((rel_type.to_string(), property.clone()), values.clone()))
318        });
319    let sampled_rel_property_histograms = advanced_statistics
320        .into_iter()
321        .flat_map(|statistics| statistics.sampled_rel_property_histograms.iter())
322        .filter_map(|((rel_type_id, property), sampled)| {
323            catalog
324                .rel_type_name(*rel_type_id)
325                .map(|rel_type| ((rel_type.to_string(), property.clone()), *sampled))
326        });
327    let property_index_statistics = catalog.property_indexes().filter_map(|index| {
328        if index.kind == IndexKind::FullText {
329            return None;
330        }
331        let statistics = advanced_statistics?;
332        let sample = statistics.index_samples.get(&index.id)?;
333        let distinct_count = sample.estimated_unique_values()?;
334        let label = catalog.label_name(index.label_id)?;
335        Some((
336            (label.to_string(), index.property.clone()),
337            OptimizerIndexStatistics {
338                index_size: sample.index_size,
339                distinct_count,
340            },
341        ))
342    });
343    let composite_index_statistics = catalog.composite_property_indexes().filter_map(|index| {
344        let statistics = advanced_statistics?;
345        let sample = statistics.index_samples.get(&index.id)?;
346        let distinct_count = sample.estimated_unique_values()?;
347        let label = catalog.label_name(index.label_id)?;
348        Some((
349            (label.to_string(), index.properties.clone()),
350            OptimizerIndexStatistics {
351                index_size: sample.index_size,
352                distinct_count,
353            },
354        ))
355    });
356    OptimizerCatalog::new(
357        OptimizerCatalogIndexes::new(
358            equality_property_indexes,
359            composite_property_indexes,
360            range_property_indexes,
361            full_text_property_indexes,
362        ),
363        OptimizerCatalogStatistics::new(
364            label_counts,
365            rel_type_counts,
366            rel_type_source_counts,
367            path_counts,
368            bounded_path_counts,
369            property_distinct_counts,
370            property_histograms,
371        )
372        .with_property_index_statistics(property_index_statistics)
373        .with_composite_index_statistics(composite_index_statistics)
374        .with_relationship_type_target_counts(rel_type_target_counts)
375        .with_path_source_distinct_counts(path_source_distinct_counts)
376        .with_path_target_distinct_counts(path_target_distinct_counts)
377        .with_bounded_path_source_distinct_counts(bounded_path_source_distinct_counts)
378        .with_bounded_path_target_distinct_counts(bounded_path_target_distinct_counts)
379        .with_relationship_property_distinct_counts(rel_property_distinct_counts)
380        .with_relationship_property_histograms(rel_property_histograms)
381        .with_sampled_property_histograms(sampled_property_histograms)
382        .with_sampled_relationship_property_histograms(sampled_rel_property_histograms),
383    )
384    .with_source_schema(catalog)
385}
386
387impl OptimizerCatalog {
388    fn with_source_schema(mut self, schema: &Catalog) -> Self {
389        self.source_schema = Some(schema.clone());
390        self
391    }
392
393    pub fn new(indexes: OptimizerCatalogIndexes, statistics: OptimizerCatalogStatistics) -> Self {
394        let joint_statistics = joint::canonical_statistics(
395            &statistics.composite_index_statistics,
396            &indexes.composite_property_indexes,
397        );
398        Self {
399            source_schema: None,
400            parameter_scalar_types: BTreeMap::new(),
401            assume_all_indexes: false,
402            equality_property_indexes: indexes.equality_property_indexes,
403            composite_property_indexes: indexes.composite_property_indexes,
404            range_property_indexes: indexes.range_property_indexes,
405            ordered_range_indexes: BTreeSet::new(),
406            ordered_composite_indexes: BTreeMap::new(),
407            full_text_property_indexes: indexes.full_text_property_indexes,
408            label_counts: statistics.label_counts,
409            rel_type_counts: statistics.rel_type_counts,
410            rel_type_source_counts: statistics.rel_type_source_counts,
411            rel_type_target_counts: statistics.rel_type_target_counts,
412            path_counts: statistics.path_counts,
413            path_source_distinct_counts: statistics.path_source_distinct_counts,
414            path_target_distinct_counts: statistics.path_target_distinct_counts,
415            bounded_path_counts: statistics.bounded_path_counts,
416            bounded_path_source_distinct_counts: statistics.bounded_path_source_distinct_counts,
417            bounded_path_target_distinct_counts: statistics.bounded_path_target_distinct_counts,
418            property_index_statistics: statistics.property_index_statistics,
419            property_equality_row_count: None,
420            composite_index_statistics: statistics.composite_index_statistics,
421            joint_statistics,
422            property_distinct_counts: statistics.property_distinct_counts,
423            rel_property_distinct_counts: statistics.rel_property_distinct_counts,
424            property_histograms: statistics.property_histograms,
425            rel_property_histograms: statistics.rel_property_histograms,
426            sampled_property_histograms: statistics.sampled_property_histograms,
427            sampled_rel_property_histograms: statistics.sampled_rel_property_histograms,
428        }
429    }
430
431    /// Supplies snapshot-local counts for a single bound equality query.
432    /// These counts are query cost inputs, not whole-index statistics. A caller
433    /// must not reuse this catalog for another predicate on the same property.
434    #[doc(hidden)]
435    pub fn with_property_equality_row_count(
436        mut self,
437        label: String,
438        property: String,
439        rows: u64,
440    ) -> Self {
441        self.property_equality_row_count = Some(((label, property), rows));
442        self
443    }
444
445    fn query_local_property_eq_rows(&self, label: &str, property: &str) -> Option<u64> {
446        self.property_equality_row_count
447            .as_ref()
448            .filter(|((local_label, local_property), _)| {
449                local_label == label && local_property == property
450            })
451            .map(|(_, rows)| *rows)
452    }
453
454    /// Opts declared range indexes into ascending `Value::cmp` delivery.
455    /// The execution engine must guarantee this for full and projected scans,
456    /// including checkpoint/delta merging. Descriptors do not imply ordering.
457    pub fn with_ordered_range_indexes(
458        mut self,
459        indexes: impl IntoIterator<Item = (String, String)>,
460    ) -> Self {
461        self.ordered_range_indexes = indexes
462            .into_iter()
463            .filter(|index| self.range_property_indexes.contains(index))
464            .collect();
465        self
466    }
467
468    /// Opt in only with enforced non-NULL ordered suffixes, a unique final key and a
469    /// read-view capability that supports complete bidirectional delivery.
470    pub fn with_ordered_composite_indexes(
471        mut self,
472        indexes: impl IntoIterator<Item = (String, Vec<(String, hawdb_core::PropertyType)>)>,
473    ) -> Self {
474        self.ordered_composite_indexes = indexes
475            .into_iter()
476            .filter_map(|(label, columns)| {
477                let properties = columns
478                    .iter()
479                    .map(|(property, _)| property.clone())
480                    .collect::<Vec<_>>();
481                (properties.len() >= 3
482                    && self
483                        .composite_property_indexes
484                        .contains(&(label.clone(), properties.clone()))
485                    && columns[columns.len() - 2..].iter().all(|(_, kind)| {
486                        matches!(
487                            kind,
488                            hawdb_core::PropertyType::Int | hawdb_core::PropertyType::String
489                        )
490                    }))
491                .then(|| {
492                    (
493                        (label, properties),
494                        columns.into_iter().map(|(_, kind)| kind).collect(),
495                    )
496                })
497            })
498            .collect();
499        self
500    }
501
502    /// Query-local proofs for opaque parameter slots; never shared across shapes.
503    #[doc(hidden)]
504    pub fn with_parameter_scalar_types(
505        mut self,
506        types: BTreeMap<Value, hawdb_core::PropertyType>,
507    ) -> Self {
508        self.parameter_scalar_types = types;
509        self
510    }
511
512    pub(super) fn scalar_type(&self, value: &Value) -> Option<hawdb_core::PropertyType> {
513        use hawdb_core::PropertyType;
514        match value {
515            Value::Int(_) => Some(PropertyType::Int),
516            Value::String(_) => Some(PropertyType::String),
517            Value::Bool(_) => Some(PropertyType::Bool),
518            _ => self.parameter_scalar_types.get(value).cloned(),
519        }
520    }
521
522    pub(super) fn optimistic() -> Self {
523        Self {
524            assume_all_indexes: true,
525            ..Self::default()
526        }
527    }
528
529    pub(super) fn has_property_index(&self, label: &str, property: &str) -> bool {
530        self.assume_all_indexes
531            || self
532                .equality_property_indexes
533                .contains(&(label.to_string(), property.to_string()))
534    }
535
536    pub(super) fn has_range_property_index(&self, label: &str, property: &str) -> bool {
537        self.assume_all_indexes
538            || self
539                .range_property_indexes
540                .contains(&(label.to_string(), property.to_string()))
541    }
542
543    pub(super) fn has_full_text_property_index(&self, label: &str, property: &str) -> bool {
544        self.assume_all_indexes
545            || self
546                .full_text_property_indexes
547                .contains(&(label.to_string(), property.to_string()))
548    }
549
550    pub(super) fn has_composite_property_index(&self, label: &str, properties: &[String]) -> bool {
551        self.assume_all_indexes
552            || self
553                .composite_property_indexes
554                .contains(&(label.to_string(), properties.to_vec()))
555    }
556
557    pub(super) fn composite_property_indexes_for_label(&self, label: &str) -> Vec<Vec<String>> {
558        if self.assume_all_indexes {
559            return Vec::new();
560        }
561        self.composite_property_indexes
562            .iter()
563            .filter_map(|(candidate_label, properties)| {
564                if candidate_label == label {
565                    Some(properties.clone())
566                } else {
567                    None
568                }
569            })
570            .collect()
571    }
572
573    pub(super) fn label_count(&self, label: &str) -> u64 {
574        self.label_counts.get(label).copied().unwrap_or(1).max(1)
575    }
576
577    pub(super) fn relationship_count(&self, rel_type: &str) -> u64 {
578        self.rel_type_counts
579            .get(rel_type)
580            .copied()
581            .unwrap_or(1)
582            .max(1)
583    }
584
585    /// Relationships a traversal of `rel_type` may visit; an untyped pattern
586    /// (empty type) may visit every relationship.
587    pub(super) fn traversable_relationship_count(&self, rel_type: &str) -> u64 {
588        if rel_type.is_empty() {
589            self.rel_type_counts
590                .values()
591                .fold(0u64, |total, count| total.saturating_add(*count))
592                .max(1)
593        } else {
594            self.relationship_count(rel_type)
595        }
596    }
597
598    pub(super) fn path_source_distinct_count(
599        &self,
600        source_label: &str,
601        rel_type: &str,
602        target_label: &str,
603    ) -> Option<u64> {
604        self.path_source_distinct_counts
605            .get(&(
606                source_label.to_string(),
607                rel_type.to_string(),
608                target_label.to_string(),
609            ))
610            .copied()
611    }
612
613    pub(super) fn path_target_distinct_count(
614        &self,
615        source_label: &str,
616        rel_type: &str,
617        target_label: &str,
618    ) -> Option<u64> {
619        self.path_target_distinct_counts
620            .get(&(
621                source_label.to_string(),
622                rel_type.to_string(),
623                target_label.to_string(),
624            ))
625            .copied()
626    }
627
628    pub(super) fn bounded_path_source_distinct_count(
629        &self,
630        source_label: &str,
631        rel_type: &str,
632        target_label: &str,
633        min_hops: usize,
634        max_hops: usize,
635    ) -> Option<u64> {
636        self.bounded_path_distinct_count(
637            &self.bounded_path_source_distinct_counts,
638            source_label,
639            rel_type,
640            target_label,
641            min_hops,
642            max_hops,
643        )
644    }
645
646    pub(super) fn bounded_path_target_distinct_count(
647        &self,
648        source_label: &str,
649        rel_type: &str,
650        target_label: &str,
651        min_hops: usize,
652        max_hops: usize,
653    ) -> Option<u64> {
654        self.bounded_path_distinct_count(
655            &self.bounded_path_target_distinct_counts,
656            source_label,
657            rel_type,
658            target_label,
659            min_hops,
660            max_hops,
661        )
662    }
663
664    pub(super) fn bounded_path_distinct_count(
665        &self,
666        counts: &BTreeMap<(String, String, String, usize), u64>,
667        source_label: &str,
668        rel_type: &str,
669        target_label: &str,
670        min_hops: usize,
671        max_hops: usize,
672    ) -> Option<u64> {
673        let mut total = 0_u64;
674        let mut found = false;
675        for hop in min_hops..=max_hops.max(min_hops) {
676            if let Some(count) = counts.get(&(
677                source_label.to_string(),
678                rel_type.to_string(),
679                target_label.to_string(),
680                hop,
681            )) {
682                found = true;
683                total = total.saturating_add(*count);
684            }
685        }
686        found.then_some(total.max(1))
687    }
688
689    pub(super) fn distinct_count(&self, label: &str, property: &str) -> u64 {
690        self.property_index_statistics
691            .get(&(label.to_string(), property.to_string()))
692            .map(|statistics| statistics.distinct_count)
693            .or_else(|| {
694                self.property_distinct_counts
695                    .get(&(label.to_string(), property.to_string()))
696                    .copied()
697            })
698            .unwrap_or_else(|| self.label_count(label).max(1))
699    }
700
701    pub(super) fn estimate_property_index_eq_rows(&self, label: &str, property: &str) -> u64 {
702        if let Some(rows) = self.query_local_property_eq_rows(label, property) {
703            return rows.min(self.label_count(label)).max(1);
704        }
705        self.property_index_statistics
706            .get(&(label.to_string(), property.to_string()))
707            .map(|statistics| {
708                statistics
709                    .index_size
710                    .div_ceil(statistics.distinct_count.max(1))
711                    .min(self.label_count(label))
712                    .max(1)
713            })
714            .unwrap_or_else(|| {
715                self.label_count(label)
716                    .div_ceil(self.distinct_count(label, property).max(1))
717                    .max(1)
718            })
719    }
720
721    pub(super) fn estimate_property_index_in_rows(
722        &self,
723        label: &str,
724        property: &str,
725        value_count: u64,
726    ) -> u64 {
727        let upper_bound = self
728            .property_index_statistics
729            .get(&(label.to_string(), property.to_string()))
730            .map_or_else(
731                || self.label_count(label),
732                |statistics| statistics.index_size.min(self.label_count(label)),
733            );
734        self.estimate_property_index_eq_rows(label, property)
735            .saturating_mul(value_count)
736            .min(upper_bound)
737            .max(1)
738    }
739
740    pub(super) fn composite_distinct_count(&self, label: &str, properties: &[String]) -> u64 {
741        self.composite_index_statistics
742            .get(&(label.to_string(), properties.to_vec()))
743            .map(|statistics| statistics.distinct_count)
744            .unwrap_or_else(|| {
745                properties
746                    .iter()
747                    .map(|property| self.distinct_count(label, property).max(1))
748                    .fold(1_u64, |product, distinct| product.saturating_mul(distinct))
749                    .max(1)
750            })
751    }
752
753    pub(super) fn estimate_composite_property_index_rows(
754        &self,
755        label: &str,
756        properties: &[String],
757    ) -> u64 {
758        self.composite_index_statistics
759            .get(&(label.to_string(), properties.to_vec()))
760            .map(|statistics| {
761                statistics
762                    .index_size
763                    .div_ceil(statistics.distinct_count.max(1))
764                    .min(self.label_count(label))
765                    .max(1)
766            })
767            .unwrap_or_else(|| {
768                self.label_count(label)
769                    .div_ceil(self.composite_distinct_count(label, properties))
770                    .max(1)
771            })
772    }
773
774    pub(super) fn estimate_composite_prefix_range_rows(
775        &self,
776        label: &str,
777        index_properties: &[String],
778        equality_properties: &[String],
779        range_property: &str,
780        lower: Option<&ValueRangeBound>,
781        upper: Option<&ValueRangeBound>,
782    ) -> u64 {
783        let label_count = self.label_count(label);
784        let equality_distinct = equality_properties
785            .iter()
786            .map(|property| self.distinct_count(label, property).max(1))
787            .fold(1u64, u64::saturating_mul);
788        let equality_rows = label_count.div_ceil(equality_distinct).max(1);
789        let range_rows = self.estimate_range_bounds_rows(label, range_property, lower, upper);
790        let estimated = equality_rows
791            .saturating_mul(range_rows)
792            .div_ceil(label_count)
793            .max(1);
794        self.composite_index_statistics
795            .get(&(label.to_string(), index_properties.to_vec()))
796            .map_or(estimated, |statistics| {
797                estimated.min(statistics.index_size.max(1))
798            })
799    }
800
801    pub(super) fn known_distinct_count(&self, label: &str, property: &str) -> Option<u64> {
802        self.property_index_statistics
803            .get(&(label.to_string(), property.to_string()))
804            .map(|statistics| statistics.distinct_count)
805            .or_else(|| {
806                self.property_distinct_counts
807                    .get(&(label.to_string(), property.to_string()))
808                    .copied()
809            })
810    }
811
812    pub(super) fn known_rel_property_distinct_count(
813        &self,
814        rel_type: &str,
815        property: &str,
816    ) -> Option<u64> {
817        self.rel_property_distinct_counts
818            .get(&(rel_type.to_string(), property.to_string()))
819            .copied()
820    }
821
822    pub(super) fn rel_property_distinct_count(&self, rel_type: &str, property: &str) -> u64 {
823        self.rel_property_distinct_counts
824            .get(&(rel_type.to_string(), property.to_string()))
825            .copied()
826            .unwrap_or_else(|| {
827                self.rel_type_counts
828                    .get(rel_type)
829                    .copied()
830                    .unwrap_or(1)
831                    .max(1)
832            })
833    }
834
835    pub(super) fn estimate_rel_property_eq_rows(
836        &self,
837        rel_type: &str,
838        property: &str,
839        input_rows: u64,
840    ) -> u64 {
841        input_rows
842            .div_ceil(self.rel_property_distinct_count(rel_type, property).max(1))
843            .max(1)
844    }
845
846    pub(super) fn estimate_rel_property_not_eq_rows(
847        &self,
848        rel_type: &str,
849        property: &str,
850        input_rows: u64,
851    ) -> u64 {
852        input_rows
853            .saturating_sub(self.estimate_rel_property_eq_rows(rel_type, property, input_rows))
854    }
855
856    pub(super) fn estimate_rel_property_in_rows(
857        &self,
858        rel_type: &str,
859        property: &str,
860        values: &[Value],
861        input_rows: u64,
862    ) -> u64 {
863        if values.is_empty() {
864            return 0;
865        }
866        let distinct_count = self.rel_property_distinct_count(rel_type, property).max(1);
867        let value_count = values
868            .iter()
869            .collect::<BTreeSet<_>>()
870            .len()
871            .min(distinct_count as usize) as u64;
872        input_rows
873            .saturating_mul(value_count)
874            .div_ceil(distinct_count)
875            .max(1)
876    }
877
878    pub(super) fn estimate_rel_property_string_match_rows(
879        &self,
880        rel_type: &str,
881        property: &str,
882        input_rows: u64,
883        max_divisor: u64,
884    ) -> u64 {
885        let divisor = self
886            .rel_property_distinct_count(rel_type, property)
887            .max(1)
888            .min(max_divisor)
889            .max(1);
890        input_rows.div_ceil(divisor).max(1)
891    }
892
893    pub(super) fn estimate_rel_property_null_rows(
894        &self,
895        rel_type: &str,
896        property: &str,
897        input_rows: u64,
898    ) -> u64 {
899        let distinct_count = self.rel_property_distinct_count(rel_type, property).max(1);
900        input_rows
901            .div_ceil(distinct_count.min(NULL_SELECTIVITY_DIVISOR_CAP))
902            .max(1)
903    }
904
905    pub(super) fn estimate_rel_property_not_null_rows(
906        &self,
907        rel_type: &str,
908        property: &str,
909        input_rows: u64,
910    ) -> u64 {
911        input_rows
912            .saturating_sub(self.estimate_rel_property_null_rows(rel_type, property, input_rows))
913            .max(1)
914    }
915
916    pub(super) fn estimate_rel_property_range_rows(
917        &self,
918        rel_type: &str,
919        property: &str,
920        op: ComparisonOp,
921        value: &Value,
922        input_rows: u64,
923    ) -> u64 {
924        let key = (rel_type.to_string(), property.to_string());
925        let Some(histogram) = self
926            .rel_property_histograms
927            .get(&key)
928            .filter(|values| !values.is_empty())
929        else {
930            return input_rows.div_ceil(RANGE_SELECTIVITY_DIVISOR).max(1);
931        };
932        let matching_values = histogram
933            .iter()
934            .filter(|candidate| compare_histogram_value(candidate, op, value))
935            .count() as u64;
936        estimate_histogram_rows(
937            input_rows,
938            matching_values,
939            histogram.len() as u64,
940            self.sampled_rel_property_histograms
941                .get(&key)
942                .copied()
943                .unwrap_or(false),
944        )
945    }
946
947    pub(super) fn estimate_range_rows(
948        &self,
949        label: &str,
950        property: &str,
951        op: ComparisonOp,
952        value: &Value,
953    ) -> u64 {
954        let label_count = self.label_count(label);
955        let key = (label.to_string(), property.to_string());
956        let Some(histogram) = self
957            .property_histograms
958            .get(&key)
959            .filter(|values| !values.is_empty())
960        else {
961            return label_count.div_ceil(RANGE_SELECTIVITY_DIVISOR).max(1);
962        };
963        let matching_values = histogram
964            .iter()
965            .filter(|candidate| compare_histogram_value(candidate, op, value))
966            .count() as u64;
967        estimate_histogram_rows(
968            label_count,
969            matching_values,
970            histogram.len() as u64,
971            self.sampled_property_histograms
972                .get(&key)
973                .copied()
974                .unwrap_or(false),
975        )
976    }
977
978    pub(super) fn estimate_property_eq_rows(
979        &self,
980        label: &str,
981        property: &str,
982        input_rows: u64,
983    ) -> u64 {
984        if let Some(rows) = self.query_local_property_eq_rows(label, property) {
985            return rows.min(input_rows).max(1);
986        }
987        input_rows
988            .div_ceil(self.distinct_count(label, property).max(1))
989            .max(1)
990    }
991
992    pub(super) fn estimate_property_not_eq_rows(
993        &self,
994        label: &str,
995        property: &str,
996        input_rows: u64,
997    ) -> u64 {
998        input_rows.saturating_sub(self.estimate_property_eq_rows(label, property, input_rows))
999    }
1000
1001    pub(super) fn estimate_property_in_rows(
1002        &self,
1003        label: &str,
1004        property: &str,
1005        values: &[Value],
1006        input_rows: u64,
1007    ) -> u64 {
1008        if values.is_empty() {
1009            return 0;
1010        }
1011        let distinct_count = self.distinct_count(label, property).max(1);
1012        let value_count = values
1013            .iter()
1014            .collect::<BTreeSet<_>>()
1015            .len()
1016            .min(distinct_count as usize) as u64;
1017        input_rows
1018            .saturating_mul(value_count)
1019            .div_ceil(distinct_count)
1020            .max(1)
1021    }
1022
1023    pub(super) fn estimate_property_string_match_rows(
1024        &self,
1025        label: &str,
1026        property: &str,
1027        input_rows: u64,
1028        max_divisor: u64,
1029    ) -> u64 {
1030        let divisor = self
1031            .distinct_count(label, property)
1032            .max(1)
1033            .min(max_divisor)
1034            .max(1);
1035        input_rows.div_ceil(divisor).max(1)
1036    }
1037
1038    pub(super) fn estimate_property_null_rows(
1039        &self,
1040        label: &str,
1041        property: &str,
1042        input_rows: u64,
1043    ) -> u64 {
1044        let distinct_count = self.distinct_count(label, property).max(1);
1045        input_rows
1046            .div_ceil(distinct_count.min(NULL_SELECTIVITY_DIVISOR_CAP))
1047            .max(1)
1048    }
1049
1050    pub(super) fn estimate_property_not_null_rows(
1051        &self,
1052        label: &str,
1053        property: &str,
1054        input_rows: u64,
1055    ) -> u64 {
1056        input_rows
1057            .saturating_sub(self.estimate_property_null_rows(label, property, input_rows))
1058            .max(1)
1059    }
1060
1061    pub(super) fn estimate_property_range_rows(
1062        &self,
1063        label: &str,
1064        property: &str,
1065        op: ComparisonOp,
1066        value: &Value,
1067        input_rows: u64,
1068    ) -> u64 {
1069        let key = (label.to_string(), property.to_string());
1070        let Some(histogram) = self
1071            .property_histograms
1072            .get(&key)
1073            .filter(|values| !values.is_empty())
1074        else {
1075            return input_rows.div_ceil(RANGE_SELECTIVITY_DIVISOR).max(1);
1076        };
1077        let matching_values = histogram
1078            .iter()
1079            .filter(|candidate| compare_histogram_value(candidate, op, value))
1080            .count() as u64;
1081        estimate_histogram_rows(
1082            input_rows,
1083            matching_values,
1084            histogram.len() as u64,
1085            self.sampled_property_histograms
1086                .get(&key)
1087                .copied()
1088                .unwrap_or(false),
1089        )
1090    }
1091
1092    pub(super) fn estimate_range_bounds_rows(
1093        &self,
1094        label: &str,
1095        property: &str,
1096        lower: Option<&ValueRangeBound>,
1097        upper: Option<&ValueRangeBound>,
1098    ) -> u64 {
1099        let label_count = self.label_count(label);
1100        let key = (label.to_string(), property.to_string());
1101        let Some(histogram) = self
1102            .property_histograms
1103            .get(&key)
1104            .filter(|values| !values.is_empty())
1105        else {
1106            return label_count.div_ceil(RANGE_SELECTIVITY_DIVISOR).max(1);
1107        };
1108        let matching_values = histogram
1109            .iter()
1110            .filter(|candidate| range_bound_matches(candidate, lower, upper))
1111            .count() as u64;
1112        estimate_histogram_rows(
1113            label_count,
1114            matching_values,
1115            histogram.len() as u64,
1116            self.sampled_property_histograms
1117                .get(&key)
1118                .copied()
1119                .unwrap_or(false),
1120        )
1121    }
1122
1123    pub(super) fn estimate_expand_rows(
1124        &self,
1125        source_label: &str,
1126        rel_type: &str,
1127        rel_properties: &BTreeMap<String, Value>,
1128        target_label: &str,
1129        min_hops: usize,
1130        max_hops: usize,
1131    ) -> ExpandEstimate {
1132        let path_count = self
1133            .path_counts
1134            .get(&(
1135                source_label.to_string(),
1136                rel_type.to_string(),
1137                target_label.to_string(),
1138            ))
1139            .copied();
1140        let rel_count = self.rel_type_counts.get(rel_type).copied().unwrap_or(1);
1141        let source_count = self
1142            .rel_type_source_counts
1143            .get(rel_type)
1144            .copied()
1145            .unwrap_or_else(|| self.label_count(source_label).max(1));
1146        let average_fanout = rel_count.div_ceil(source_count.max(1)).max(1);
1147        let one_hop = path_count.unwrap_or_else(|| {
1148            self.label_count(source_label)
1149                .min(self.label_count(target_label))
1150                .max(1)
1151        });
1152        let property_distinct_product = rel_properties
1153            .keys()
1154            .map(|property| self.rel_property_distinct_count(rel_type, property).max(1))
1155            .fold(1_u64, |acc, value| acc.saturating_mul(value))
1156            .max(1);
1157        let mut estimated_rows = 0_u64;
1158        let mut hop_rows = one_hop.max(1);
1159        let mut hop_estimates = Vec::new();
1160        for hop in 1..=max_hops.max(1) {
1161            let exact_hop_rows = self
1162                .bounded_path_counts
1163                .get(&(
1164                    source_label.to_string(),
1165                    rel_type.to_string(),
1166                    target_label.to_string(),
1167                    hop,
1168                ))
1169                .copied();
1170            let current_hop_rows = exact_hop_rows
1171                .unwrap_or(hop_rows)
1172                .div_ceil(property_distinct_product)
1173                .max(1);
1174            hop_estimates.push(HopEstimate {
1175                hop,
1176                rows: current_hop_rows,
1177                exact: exact_hop_rows.is_some(),
1178            });
1179            if hop >= min_hops {
1180                estimated_rows = estimated_rows.saturating_add(current_hop_rows);
1181            }
1182            hop_rows = current_hop_rows.max(1).saturating_mul(average_fanout);
1183        }
1184        ExpandEstimate {
1185            path_count,
1186            rel_count,
1187            source_count,
1188            average_fanout,
1189            property_distinct_product,
1190            estimated_rows: estimated_rows.max(1),
1191            hop_estimates,
1192        }
1193    }
1194}
1195
1196fn estimate_histogram_rows(
1197    input_rows: u64,
1198    matching_values: u64,
1199    histogram_values: u64,
1200    sampled: bool,
1201) -> u64 {
1202    // A sampled CDF is finite evidence rather than an exhaustive rank table. Add-one
1203    // smoothing shrinks it toward the existing 50% fallback by a weight determined by
1204    // the actual sample size, while leaving complete histograms exact.
1205    let (matching_values, histogram_values) = if sampled {
1206        (
1207            matching_values.saturating_add(SAMPLED_HISTOGRAM_MATCH_PSEUDOCOUNT),
1208            histogram_values.saturating_add(SAMPLED_HISTOGRAM_TOTAL_PSEUDOCOUNT),
1209        )
1210    } else {
1211        (matching_values, histogram_values)
1212    };
1213    input_rows
1214        .saturating_mul(matching_values)
1215        .div_ceil(histogram_values.max(1))
1216        .max(1)
1217}
1218
1219impl OptimizerCatalogIndexes {
1220    pub fn new(
1221        equality_property_indexes: impl IntoIterator<Item = (String, String)>,
1222        composite_property_indexes: impl IntoIterator<Item = (String, Vec<String>)>,
1223        range_property_indexes: impl IntoIterator<Item = (String, String)>,
1224        full_text_property_indexes: impl IntoIterator<Item = (String, String)>,
1225    ) -> Self {
1226        Self {
1227            equality_property_indexes: equality_property_indexes.into_iter().collect(),
1228            composite_property_indexes: composite_property_indexes.into_iter().collect(),
1229            range_property_indexes: range_property_indexes.into_iter().collect(),
1230            full_text_property_indexes: full_text_property_indexes.into_iter().collect(),
1231        }
1232    }
1233}
1234
1235impl OptimizerCatalogStatistics {
1236    pub fn new(
1237        label_counts: impl IntoIterator<Item = (String, u64)>,
1238        rel_type_counts: impl IntoIterator<Item = (String, u64)>,
1239        rel_type_source_counts: impl IntoIterator<Item = (String, u64)>,
1240        path_counts: impl IntoIterator<Item = ((String, String, String), u64)>,
1241        bounded_path_counts: impl IntoIterator<Item = ((String, String, String, usize), u64)>,
1242        property_distinct_counts: impl IntoIterator<Item = ((String, String), u64)>,
1243        property_histograms: impl IntoIterator<Item = ((String, String), Vec<Value>)>,
1244    ) -> Self {
1245        Self {
1246            label_counts: label_counts.into_iter().collect(),
1247            rel_type_counts: rel_type_counts.into_iter().collect(),
1248            rel_type_source_counts: rel_type_source_counts.into_iter().collect(),
1249            rel_type_target_counts: BTreeMap::new(),
1250            path_counts: path_counts.into_iter().collect(),
1251            path_source_distinct_counts: BTreeMap::new(),
1252            path_target_distinct_counts: BTreeMap::new(),
1253            bounded_path_counts: bounded_path_counts.into_iter().collect(),
1254            bounded_path_source_distinct_counts: BTreeMap::new(),
1255            bounded_path_target_distinct_counts: BTreeMap::new(),
1256            property_index_statistics: BTreeMap::new(),
1257            composite_index_statistics: BTreeMap::new(),
1258            property_distinct_counts: property_distinct_counts.into_iter().collect(),
1259            rel_property_distinct_counts: BTreeMap::new(),
1260            property_histograms: property_histograms.into_iter().collect(),
1261            rel_property_histograms: BTreeMap::new(),
1262            sampled_property_histograms: BTreeMap::new(),
1263            sampled_rel_property_histograms: BTreeMap::new(),
1264        }
1265    }
1266
1267    pub fn with_property_index_statistics(
1268        mut self,
1269        statistics: impl IntoIterator<Item = ((String, String), OptimizerIndexStatistics)>,
1270    ) -> Self {
1271        self.property_index_statistics = statistics.into_iter().collect();
1272        self
1273    }
1274
1275    pub fn with_composite_index_statistics(
1276        mut self,
1277        statistics: impl IntoIterator<Item = ((String, Vec<String>), OptimizerIndexStatistics)>,
1278    ) -> Self {
1279        self.composite_index_statistics = statistics.into_iter().collect();
1280        self
1281    }
1282
1283    pub fn with_relationship_property_distinct_counts(
1284        mut self,
1285        rel_property_distinct_counts: impl IntoIterator<Item = ((String, String), u64)>,
1286    ) -> Self {
1287        self.rel_property_distinct_counts = rel_property_distinct_counts.into_iter().collect();
1288        self
1289    }
1290
1291    pub fn with_relationship_type_target_counts(
1292        mut self,
1293        rel_type_target_counts: impl IntoIterator<Item = (String, u64)>,
1294    ) -> Self {
1295        self.rel_type_target_counts = rel_type_target_counts.into_iter().collect();
1296        self
1297    }
1298
1299    pub fn with_path_source_distinct_counts(
1300        mut self,
1301        path_source_distinct_counts: impl IntoIterator<Item = ((String, String, String), u64)>,
1302    ) -> Self {
1303        self.path_source_distinct_counts = path_source_distinct_counts.into_iter().collect();
1304        self
1305    }
1306
1307    pub fn with_path_target_distinct_counts(
1308        mut self,
1309        path_target_distinct_counts: impl IntoIterator<Item = ((String, String, String), u64)>,
1310    ) -> Self {
1311        self.path_target_distinct_counts = path_target_distinct_counts.into_iter().collect();
1312        self
1313    }
1314
1315    pub fn with_bounded_path_source_distinct_counts(
1316        mut self,
1317        bounded_path_source_distinct_counts: impl IntoIterator<
1318            Item = ((String, String, String, usize), u64),
1319        >,
1320    ) -> Self {
1321        self.bounded_path_source_distinct_counts =
1322            bounded_path_source_distinct_counts.into_iter().collect();
1323        self
1324    }
1325
1326    pub fn with_bounded_path_target_distinct_counts(
1327        mut self,
1328        bounded_path_target_distinct_counts: impl IntoIterator<
1329            Item = ((String, String, String, usize), u64),
1330        >,
1331    ) -> Self {
1332        self.bounded_path_target_distinct_counts =
1333            bounded_path_target_distinct_counts.into_iter().collect();
1334        self
1335    }
1336
1337    pub fn with_relationship_property_histograms(
1338        mut self,
1339        rel_property_histograms: impl IntoIterator<Item = ((String, String), Vec<Value>)>,
1340    ) -> Self {
1341        self.rel_property_histograms = rel_property_histograms.into_iter().collect();
1342        self
1343    }
1344
1345    pub fn with_sampled_property_histograms(
1346        mut self,
1347        sampled_property_histograms: impl IntoIterator<Item = ((String, String), bool)>,
1348    ) -> Self {
1349        self.sampled_property_histograms = sampled_property_histograms.into_iter().collect();
1350        self
1351    }
1352
1353    pub fn with_sampled_relationship_property_histograms(
1354        mut self,
1355        sampled_rel_property_histograms: impl IntoIterator<Item = ((String, String), bool)>,
1356    ) -> Self {
1357        self.sampled_rel_property_histograms =
1358            sampled_rel_property_histograms.into_iter().collect();
1359        self
1360    }
1361}
1362
1363#[cfg(test)]
1364mod tests {
1365    use super::*;
1366
1367    #[test]
1368    fn graph_statistics_catalog_keeps_basic_counts_when_advanced_stats_are_incomplete() {
1369        let mut source_catalog = Catalog::default();
1370        let memory = source_catalog.get_or_create_label("Memory");
1371        let mut statistics = GraphStatistics {
1372            advanced_statistics_complete: false,
1373            label_counts: BTreeMap::from([(memory, 64)]),
1374            property_distinct_counts: BTreeMap::from([((memory, "kind".to_string()), 4)]),
1375            property_histograms: BTreeMap::from([(
1376                (memory, "kind".to_string()),
1377                vec![Value::String("note".to_string())],
1378            )]),
1379            ..GraphStatistics::default()
1380        };
1381
1382        let incomplete = optimizer_catalog_from_graph_statistics(&source_catalog, &statistics);
1383        assert_eq!(incomplete.label_count("Memory"), 64);
1384        assert_eq!(incomplete.known_distinct_count("Memory", "kind"), None);
1385        assert!(incomplete.property_histograms.is_empty());
1386
1387        statistics.advanced_statistics_complete = true;
1388        let complete = optimizer_catalog_from_graph_statistics(&source_catalog, &statistics);
1389        assert_eq!(complete.label_count("Memory"), 64);
1390        assert_eq!(complete.known_distinct_count("Memory", "kind"), Some(4));
1391        assert_eq!(
1392            complete.property_histograms,
1393            BTreeMap::from([(
1394                ("Memory".to_string(), "kind".to_string()),
1395                vec![Value::String("note".to_string())],
1396            )])
1397        );
1398    }
1399
1400    #[test]
1401    fn range_cardinality_honors_half_open_histogram_bounds() {
1402        let catalog = OptimizerCatalog::new(
1403            OptimizerCatalogIndexes::default(),
1404            OptimizerCatalogStatistics::new(
1405                [("Memory".to_string(), 1_000)],
1406                [],
1407                [],
1408                [],
1409                [],
1410                [],
1411                [(
1412                    ("Memory".to_string(), "created_at".to_string()),
1413                    (0..100).map(Value::Int).collect::<Vec<_>>(),
1414                )],
1415            ),
1416        );
1417
1418        assert_eq!(
1419            catalog.estimate_range_bounds_rows(
1420                "Memory",
1421                "created_at",
1422                Some(&(Value::Int(10), true)),
1423                Some(&(Value::Int(20), false)),
1424            ),
1425            100
1426        );
1427    }
1428
1429    #[test]
1430    fn sampled_histograms_shrink_range_selectivity_toward_default() {
1431        let property_key = ("Memory".to_string(), "score".to_string());
1432        let rel_property_key = ("MENTIONS".to_string(), "score".to_string());
1433        let histogram = (0..100).map(Value::Int).collect::<Vec<_>>();
1434        let statistics = OptimizerCatalogStatistics::new(
1435            [("Memory".to_string(), 1_000)],
1436            [],
1437            [],
1438            [],
1439            [],
1440            [(property_key.clone(), 100)],
1441            [(property_key.clone(), histogram.clone())],
1442        )
1443        .with_relationship_property_histograms([(rel_property_key.clone(), histogram)]);
1444        let exhaustive =
1445            OptimizerCatalog::new(OptimizerCatalogIndexes::default(), statistics.clone());
1446        let sampled = OptimizerCatalog::new(
1447            OptimizerCatalogIndexes::default(),
1448            statistics
1449                .with_sampled_property_histograms([(property_key, true)])
1450                .with_sampled_relationship_property_histograms([(rel_property_key, true)]),
1451        );
1452
1453        assert_eq!(
1454            exhaustive.estimate_range_rows("Memory", "score", ComparisonOp::Lt, &Value::Int(10)),
1455            100
1456        );
1457        assert_eq!(
1458            sampled.estimate_range_rows("Memory", "score", ComparisonOp::Lt, &Value::Int(10)),
1459            108
1460        );
1461        assert_eq!(
1462            sampled.estimate_property_range_rows(
1463                "Memory",
1464                "score",
1465                ComparisonOp::Lt,
1466                &Value::Int(10),
1467                1_000,
1468            ),
1469            108
1470        );
1471        assert_eq!(
1472            sampled.estimate_range_bounds_rows(
1473                "Memory",
1474                "score",
1475                None,
1476                Some(&(Value::Int(10), false)),
1477            ),
1478            108
1479        );
1480        assert_eq!(
1481            exhaustive.estimate_rel_property_range_rows(
1482                "MENTIONS",
1483                "score",
1484                ComparisonOp::Lt,
1485                &Value::Int(10),
1486                1_000,
1487            ),
1488            100
1489        );
1490        assert_eq!(
1491            sampled.estimate_rel_property_range_rows(
1492                "MENTIONS",
1493                "score",
1494                ComparisonOp::Lt,
1495                &Value::Int(10),
1496                1_000,
1497            ),
1498            108
1499        );
1500    }
1501
1502    #[test]
1503    fn index_cardinality_uses_sparse_index_size_and_joint_ndv() {
1504        let statistics = OptimizerCatalogStatistics {
1505            label_counts: BTreeMap::from([("Memory".to_string(), 100)]),
1506            property_index_statistics: BTreeMap::from([(
1507                ("Memory".to_string(), "kind".to_string()),
1508                OptimizerIndexStatistics {
1509                    index_size: 10,
1510                    distinct_count: 2,
1511                },
1512            )]),
1513            composite_index_statistics: BTreeMap::from([(
1514                (
1515                    "Memory".to_string(),
1516                    vec!["kind".to_string(), "source_id".to_string()],
1517                ),
1518                OptimizerIndexStatistics {
1519                    index_size: 8,
1520                    distinct_count: 4,
1521                },
1522            )]),
1523            ..OptimizerCatalogStatistics::default()
1524        };
1525        let catalog = OptimizerCatalog::new(OptimizerCatalogIndexes::default(), statistics);
1526
1527        assert_eq!(catalog.estimate_property_index_eq_rows("Memory", "kind"), 5);
1528        assert_eq!(
1529            catalog.estimate_property_index_in_rows("Memory", "kind", 10),
1530            10
1531        );
1532        assert_eq!(
1533            catalog.estimate_composite_property_index_rows(
1534                "Memory",
1535                &["kind".to_string(), "source_id".to_string()],
1536            ),
1537            2
1538        );
1539    }
1540
1541    #[test]
1542    fn query_local_equality_counts_do_not_replace_whole_index_statistics() {
1543        let catalog = OptimizerCatalog::new(
1544            OptimizerCatalogIndexes::default(),
1545            OptimizerCatalogStatistics {
1546                label_counts: BTreeMap::from([("Item".into(), 100)]),
1547                property_index_statistics: BTreeMap::from([(
1548                    ("Item".into(), "id".into()),
1549                    OptimizerIndexStatistics {
1550                        index_size: 90,
1551                        distinct_count: 10,
1552                    },
1553                )]),
1554                ..OptimizerCatalogStatistics::default()
1555            },
1556        );
1557        let local = catalog
1558            .clone()
1559            .with_property_equality_row_count("Item".into(), "id".into(), 2);
1560        assert_eq!(catalog.estimate_property_index_eq_rows("Item", "id"), 9);
1561        assert_eq!(local.estimate_property_index_eq_rows("Item", "id"), 2);
1562        assert_eq!(local.estimate_property_eq_rows("Item", "id", 100), 2);
1563        assert_eq!(
1564            local.property_index_statistics,
1565            catalog.property_index_statistics
1566        );
1567        assert_eq!(
1568            local.estimate_property_index_eq_rows("Item", "other"),
1569            catalog.estimate_property_index_eq_rows("Item", "other")
1570        );
1571        let empty = catalog
1572            .clone()
1573            .with_property_equality_row_count("Item".into(), "id".into(), 0);
1574        assert_eq!(empty.estimate_property_index_eq_rows("Item", "id"), 1);
1575    }
1576}