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