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