Skip to main content

hawdb_core/
schema.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 crate::{LogicalType, Value};
16use std::collections::BTreeMap;
17use std::sync::Arc;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub struct LabelId(pub u32);
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub struct RelTypeId(pub u32);
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub struct TableId(pub u32);
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct Label {
30    pub id: LabelId,
31    pub name: String,
32}
33
34/// The lookup directory shares the immutable symbol rather than allocating a
35/// second name. Ordering and borrowed lookup retain their string semantics.
36#[derive(Debug, Clone)]
37struct LabelNameKey(Arc<Label>);
38
39impl std::borrow::Borrow<str> for LabelNameKey {
40    fn borrow(&self) -> &str {
41        &self.0.name
42    }
43}
44
45impl PartialEq for LabelNameKey {
46    fn eq(&self, other: &Self) -> bool {
47        self.0.name == other.0.name
48    }
49}
50
51impl Eq for LabelNameKey {}
52
53impl PartialOrd for LabelNameKey {
54    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
55        Some(self.cmp(other))
56    }
57}
58
59impl Ord for LabelNameKey {
60    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
61        self.0.name.cmp(&other.0.name)
62    }
63}
64
65/// Admission token for a retained immutable symbol. Standalone callers remain
66/// responsible for their allocation policy and complete backing capacity.
67#[doc(hidden)]
68pub trait RetainedLabelAllocation {
69    fn bytes(&self) -> usize;
70}
71
72/// Own one admitted immutable symbol without retaining the catalog directory.
73#[doc(hidden)]
74#[derive(Debug)]
75pub struct RetainedLabelName<A> {
76    label: Arc<Label>,
77    _allocation: A,
78}
79
80impl<A> RetainedLabelName<A> {
81    pub fn id(&self) -> LabelId {
82        self.label.id
83    }
84
85    pub fn name(&self) -> &str {
86        &self.label.name
87    }
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct RelType {
92    pub id: RelTypeId,
93    pub name: String,
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
97pub struct IndexId(pub u32);
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
100pub struct ConstraintId(pub u32);
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
103pub struct PropertyId(pub u32);
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
106pub enum IndexKind {
107    Equality,
108    Range,
109    FullText,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
113pub enum ConstraintKind {
114    NodePropertyUnique,
115    NodePropertyExists,
116    RelationshipPropertyUnique,
117    RelationshipPropertyExists,
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
121pub enum ConstraintSubject {
122    Node(LabelId),
123    Relationship(RelTypeId),
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
127pub enum TableKind {
128    Node,
129    Relationship,
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub enum SchemaObjectState {
134    DeleteOnly,
135    WriteOnly,
136    Backfill,
137    Validating,
138    Public,
139    Gc,
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
143pub enum PropertyType {
144    Any,
145    Bool,
146    Int,
147    Float,
148    /// Application string eligible for statistics; exposed as VARCHAR-like DDL.
149    String,
150    /// Unbounded text payload. Optimizer value statistics intentionally skip it.
151    Text,
152    List,
153    Vector(crate::VectorDimension),
154}
155
156impl PropertyType {
157    pub const fn logical_type(self) -> LogicalType {
158        match self {
159            Self::Any => LogicalType::Any,
160            Self::Bool => LogicalType::Boolean,
161            Self::Int => LogicalType::Int64,
162            Self::Float => LogicalType::Float64,
163            Self::String => LogicalType::String,
164            Self::Text => LogicalType::Text,
165            Self::List => LogicalType::List,
166            Self::Vector(dimension) => LogicalType::Vector(dimension),
167        }
168    }
169}
170
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct IndexDescriptor {
173    pub id: IndexId,
174    pub label_id: LabelId,
175    pub property: String,
176    pub kind: IndexKind,
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct CompositeIndexDescriptor {
181    pub id: IndexId,
182    pub label_id: LabelId,
183    pub properties: Vec<String>,
184}
185
186/// A compact, payload-free sample for one explicit property index.
187///
188/// `index_size`, `unique_values`, and `sample_size` describe one coherent
189/// sampling epoch. Mutations after that epoch only advance
190/// `updates_since_sample`; they never rewrite the sampled counters in place.
191#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
192pub struct IndexStatisticsSample {
193    pub index_size: u64,
194    pub unique_values: u64,
195    pub sample_size: u64,
196    pub updates_since_sample: u64,
197}
198
199impl IndexStatisticsSample {
200    pub const STALE_UPDATE_PERCENT: u64 = 5;
201
202    pub fn exact(index_size: u64, unique_values: u64) -> Self {
203        Self {
204            index_size,
205            unique_values,
206            sample_size: index_size,
207            updates_since_sample: 0,
208        }
209    }
210
211    pub fn is_valid(self) -> bool {
212        self.sample_size <= self.index_size
213            && self.unique_values <= self.sample_size
214            && (self.sample_size != 0 || self.unique_values == 0)
215    }
216
217    pub fn max_fresh_updates(self) -> u64 {
218        self.index_size
219            .saturating_mul(Self::STALE_UPDATE_PERCENT)
220            .div_ceil(100)
221            .max(1)
222    }
223
224    pub fn is_stale(self) -> bool {
225        self.updates_since_sample > self.max_fresh_updates()
226    }
227
228    pub fn estimated_unique_values(self) -> Option<u64> {
229        if !self.is_valid() || self.is_stale() || self.sample_size == 0 {
230            return None;
231        }
232        Some(
233            self.unique_values
234                .saturating_mul(self.index_size)
235                .div_ceil(self.sample_size)
236                .clamp(1, self.index_size.max(1)),
237        )
238    }
239}
240
241#[derive(Debug, Clone, PartialEq, Eq)]
242pub struct ConstraintDescriptor {
243    pub id: ConstraintId,
244    pub subject: ConstraintSubject,
245    pub property: String,
246    pub kind: ConstraintKind,
247}
248
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct TableDescriptor {
251    pub id: TableId,
252    pub name: String,
253    pub kind: TableKind,
254    pub state: SchemaObjectState,
255}
256
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct PropertyDescriptor {
259    pub id: PropertyId,
260    pub table_id: TableId,
261    pub name: String,
262    pub value_type: PropertyType,
263    pub nullable: bool,
264    pub state: SchemaObjectState,
265    /// Value written when a record of this table is created without the
266    /// property. `None` (the only state older catalogs can encode) means the
267    /// property stays absent.
268    pub default: Option<DeclaredPropertyDefault>,
269}
270
271/// A property default as declared by DDL.
272#[derive(Debug, Clone, PartialEq, Eq)]
273pub struct DeclaredPropertyDefault {
274    /// Applied to records created after the declaration.
275    pub value: PropertyDefault,
276    /// Written to records that already existed without the property when the
277    /// default was declared. Resolved once at declaration time, so a
278    /// `current_timestamp()` backfill writes one instant across every bounded
279    /// maintenance run (Kùzu `ALTER TABLE ... ADD ... DEFAULT` semantics).
280    pub backfill_value: Value,
281}
282
283/// One declared property descriptor, resolved to its table name, as exposed
284/// by catalog introspection.
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct PropertySchema {
287    pub table_kind: TableKind,
288    pub table: String,
289    pub property: String,
290    pub value_type: PropertyType,
291    pub nullable: bool,
292    pub state: SchemaObjectState,
293    /// The declared default, if any. Older catalogs report `None`.
294    pub default: Option<DeclaredPropertyDefault>,
295}
296
297impl DeclaredPropertyDefault {
298    /// Resolves `value` at the current creation clock for a new declaration.
299    pub fn declare(value: PropertyDefault) -> Self {
300        let backfill_value = value.resolve(PropertyDefault::creation_clock());
301        Self {
302            value,
303            backfill_value,
304        }
305    }
306}
307
308/// A declared property default, applied only when a node or relationship is
309/// created without the property. An explicit NULL in the creating write is
310/// kept; the default never fills properties at read time.
311#[derive(Debug, Clone, PartialEq, Eq)]
312pub enum PropertyDefault {
313    /// A constant literal (bool, integer, float, string or list of those).
314    Value(Value),
315    /// `current_timestamp()`: the representation HawDB's own
316    /// `current_timestamp()` produces (`Int` epoch nanoseconds), one value per
317    /// writing transaction, truncated to whole milliseconds (Kùzu semantics).
318    CurrentTimestamp,
319}
320
321impl PropertyDefault {
322    /// Resolves the default for a record created by a transaction whose
323    /// creation clock is `clock`.
324    pub fn resolve(&self, clock: crate::temporal::PlainDateTime) -> Value {
325        match self {
326            Self::Value(value) => value.clone(),
327            Self::CurrentTimestamp => Value::Int(
328                crate::temporal::types::epoch_millis(clock.assume_utc())
329                    .saturating_mul(1_000_000)
330                    .max(0),
331            ),
332        }
333    }
334
335    /// The `current_timestamp()` creation clock: the statement clock truncated
336    /// to whole milliseconds, as a timezone-naive UTC timestamp.
337    pub fn creation_clock() -> crate::temporal::PlainDateTime {
338        let now = crate::temporal::statement_now();
339        let millis = crate::temporal::types::epoch_millis(now);
340        crate::temporal::types::utc_datetime(
341            crate::temporal::types::datetime_from_millis(millis).unwrap_or(now),
342        )
343    }
344
345    /// Whether this descriptor state applies defaults to newly created records.
346    pub const fn applies_in(state: SchemaObjectState) -> bool {
347        matches!(
348            state,
349            SchemaObjectState::WriteOnly
350                | SchemaObjectState::Backfill
351                | SchemaObjectState::Validating
352                | SchemaObjectState::Public
353        )
354    }
355}
356
357impl std::fmt::Display for PropertyDefault {
358    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
359        match self {
360            Self::Value(value) => write!(f, "{value:?}"),
361            Self::CurrentTimestamp => f.write_str("current_timestamp()"),
362        }
363    }
364}
365
366#[derive(Debug, Default, Clone, PartialEq, Eq)]
367pub struct BasicGraphStatistics {
368    pub computed_at_commit_epoch: u64,
369    pub node_count: u64,
370    pub relationship_count: u64,
371    pub label_counts: BTreeMap<LabelId, u64>,
372    pub rel_type_counts: BTreeMap<RelTypeId, u64>,
373}
374
375/// Whether a complete advanced-statistics snapshot describes the current graph epoch.
376#[derive(Debug, Clone, Copy, PartialEq, Eq)]
377pub enum AdvancedStatisticsFreshness {
378    /// The snapshot is complete and was computed at the current graph epoch.
379    Fresh,
380    /// A complete snapshot exists, but it describes a different graph epoch.
381    Stale,
382    /// No complete advanced-statistics snapshot is available.
383    Unavailable,
384}
385
386impl AdvancedStatisticsFreshness {
387    pub const fn as_str(self) -> &'static str {
388        match self {
389            Self::Fresh => "fresh",
390            Self::Stale => "stale",
391            Self::Unavailable => "unavailable",
392        }
393    }
394}
395
396#[derive(Debug, Default, Clone, PartialEq, Eq)]
397pub struct GraphStatistics {
398    pub computed_at_commit_epoch: u64,
399    pub advanced_statistics_complete: bool,
400    pub histogram_sample_limit: usize,
401    pub node_count: u64,
402    pub relationship_count: u64,
403    pub label_counts: BTreeMap<LabelId, u64>,
404    pub rel_type_counts: BTreeMap<RelTypeId, u64>,
405    pub rel_type_source_counts: BTreeMap<RelTypeId, u64>,
406    pub rel_type_target_counts: BTreeMap<RelTypeId, u64>,
407    pub path_counts: BTreeMap<(LabelId, RelTypeId, LabelId), u64>,
408    pub path_source_distinct_counts: BTreeMap<(LabelId, RelTypeId, LabelId), u64>,
409    pub path_target_distinct_counts: BTreeMap<(LabelId, RelTypeId, LabelId), u64>,
410    pub bounded_path_counts: BTreeMap<(LabelId, RelTypeId, LabelId, usize), u64>,
411    /// Complete enumeration of homogeneous directed walks through this hop.
412    /// Missing tuples within 1..=hop are zero in this statistics snapshot. None means unavailable,
413    /// truncated, or legacy statistics whose coverage is unknown.
414    pub bounded_path_complete_through_hop: Option<usize>,
415    pub bounded_path_source_distinct_counts: BTreeMap<(LabelId, RelTypeId, LabelId, usize), u64>,
416    pub bounded_path_target_distinct_counts: BTreeMap<(LabelId, RelTypeId, LabelId, usize), u64>,
417    pub index_samples: BTreeMap<IndexId, IndexStatisticsSample>,
418    pub property_distinct_counts: BTreeMap<(LabelId, String), u64>,
419    pub rel_property_distinct_counts: BTreeMap<(RelTypeId, String), u64>,
420    pub property_histograms: BTreeMap<(LabelId, String), Vec<Value>>,
421    pub rel_property_histograms: BTreeMap<(RelTypeId, String), Vec<Value>>,
422    pub sampled_property_histograms: BTreeMap<(LabelId, String), bool>,
423    pub sampled_rel_property_histograms: BTreeMap<(RelTypeId, String), bool>,
424    pub property_distributions: BTreeMap<(LabelId, String), crate::CompressedHistogram>,
425    pub rel_property_distributions: BTreeMap<(RelTypeId, String), crate::CompressedHistogram>,
426}
427
428impl GraphStatistics {
429    /// Classifies only advanced statistics; basic counts may be newer than this snapshot.
430    pub fn advanced_statistics_freshness(
431        &self,
432        current_commit_epoch: u64,
433    ) -> AdvancedStatisticsFreshness {
434        if !self.advanced_statistics_complete {
435            AdvancedStatisticsFreshness::Unavailable
436        } else if self.computed_at_commit_epoch == current_commit_epoch {
437            AdvancedStatisticsFreshness::Fresh
438        } else {
439            AdvancedStatisticsFreshness::Stale
440        }
441    }
442
443    /// Returns the observable lag without underflowing on an invalid future snapshot epoch.
444    pub fn advanced_statistics_commit_lag(&self, current_commit_epoch: u64) -> u64 {
445        current_commit_epoch.saturating_sub(self.computed_at_commit_epoch)
446    }
447}
448
449mod snapshot;
450#[cfg(test)]
451mod snapshot_tests;
452
453#[derive(Debug, Default, Clone, PartialEq, Eq)]
454pub struct Catalog {
455    labels_by_name: snapshot::CatalogSnapshot<BTreeMap<LabelNameKey, LabelId>>,
456    labels: snapshot::CatalogSnapshot<Vec<Arc<Label>>>,
457    rel_types_by_name: snapshot::CatalogSnapshot<BTreeMap<String, RelTypeId>>,
458    rel_types: snapshot::CatalogSnapshot<Vec<RelType>>,
459    tables_by_key: snapshot::CatalogSnapshot<BTreeMap<(TableKind, String), TableId>>,
460    tables: snapshot::CatalogSnapshot<Vec<TableDescriptor>>,
461    properties_by_key: snapshot::CatalogSnapshot<BTreeMap<(TableId, String), PropertyId>>,
462    properties: snapshot::CatalogSnapshot<Vec<PropertyDescriptor>>,
463    property_indexes_by_key:
464        snapshot::CatalogSnapshot<BTreeMap<(LabelId, String, IndexKind), IndexId>>,
465    property_indexes: snapshot::CatalogSnapshot<Vec<IndexDescriptor>>,
466    composite_property_indexes_by_key:
467        snapshot::CatalogSnapshot<BTreeMap<(LabelId, Vec<String>), IndexId>>,
468    composite_property_indexes: snapshot::CatalogSnapshot<Vec<CompositeIndexDescriptor>>,
469    constraints_by_key: snapshot::CatalogSnapshot<
470        BTreeMap<(ConstraintSubject, String, ConstraintKind), ConstraintId>,
471    >,
472    constraints: snapshot::CatalogSnapshot<Vec<ConstraintDescriptor>>,
473}
474
475impl Catalog {
476    pub fn is_empty(&self) -> bool {
477        self.labels_by_name.is_empty()
478            && self.rel_types_by_name.is_empty()
479            && self.tables_by_key.is_empty()
480            && self.properties_by_key.is_empty()
481            && self.property_indexes_by_key.is_empty()
482            && self.composite_property_indexes_by_key.is_empty()
483            && self.constraints_by_key.is_empty()
484    }
485
486    pub fn get_or_create_label(&mut self, name: &str) -> LabelId {
487        if let Some(id) = self.labels_by_name.get(name) {
488            return *id;
489        }
490        let id = LabelId(self.labels.len() as u32);
491        let label = Arc::new(Label {
492            id,
493            name: name.to_string(),
494        });
495        self.labels_by_name
496            .insert(LabelNameKey(Arc::clone(&label)), id);
497        self.labels.push(label);
498        id
499    }
500
501    pub fn label_id(&self, name: &str) -> Option<LabelId> {
502        self.labels_by_name.get(name).copied()
503    }
504
505    pub fn label_name(&self, id: LabelId) -> Option<&str> {
506        self.labels
507            .get(id.0 as usize)
508            .map(|label| label.name.as_str())
509    }
510
511    pub fn labels(&self) -> impl Iterator<Item = &Label> {
512        self.labels.iter().map(Arc::as_ref)
513    }
514
515    /// Complete immutable symbol backing capacity, observed without capture.
516    #[doc(hidden)]
517    pub fn retained_label_name_capacity_bytes(&self, id: LabelId) -> crate::Result<Option<usize>> {
518        self.labels
519            .get(id.0 as usize)
520            .map(|label| Self::label_name_capacity_bytes(label))
521            .transpose()
522    }
523
524    fn label_name_capacity_bytes(label: &Label) -> crate::Result<usize> {
525        std::mem::size_of::<Label>()
526            .checked_add(2 * std::mem::size_of::<usize>())
527            .and_then(|bytes| bytes.checked_add(label.name.capacity()))
528            .ok_or_else(|| crate::HawDBError::Execution("label capacity overflow".into()))
529    }
530
531    /// Reserve a label's complete name capacity before retaining its immutable
532    /// owner. Missing IDs do not invoke admission; host refusals stay typed.
533    /// Container and adapter metadata require separate caller admission.
534    #[doc(hidden)]
535    pub fn retain_label_name_with_admission<A: RetainedLabelAllocation, E>(
536        &self,
537        id: LabelId,
538        allocate: impl FnOnce(usize) -> std::result::Result<A, E>,
539    ) -> std::result::Result<Option<RetainedLabelName<A>>, E>
540    where
541        E: From<crate::HawDBError>,
542    {
543        let Some(label) = self.labels.get(id.0 as usize) else {
544            return Ok(None);
545        };
546        let bytes = Self::label_name_capacity_bytes(label)?;
547        let allocation = allocate(bytes)?;
548        if allocation.bytes() < bytes {
549            return Err(crate::HawDBError::Execution(
550                "retained label admission returned an insufficient allocation permit".into(),
551            )
552            .into());
553        }
554        Ok(Some(RetainedLabelName {
555            label: Arc::clone(label),
556            _allocation: allocation,
557        }))
558    }
559
560    pub fn get_or_create_rel_type(&mut self, name: &str) -> RelTypeId {
561        if let Some(id) = self.rel_types_by_name.get(name) {
562            return *id;
563        }
564        let id = RelTypeId(self.rel_types.len() as u32);
565        self.rel_types.push(RelType {
566            id,
567            name: name.to_string(),
568        });
569        self.rel_types_by_name.insert(name.to_string(), id);
570        id
571    }
572
573    pub fn rel_type_id(&self, name: &str) -> Option<RelTypeId> {
574        self.rel_types_by_name.get(name).copied()
575    }
576
577    pub fn rel_type_name(&self, id: RelTypeId) -> Option<&str> {
578        self.rel_types
579            .get(id.0 as usize)
580            .map(|rel_type| rel_type.name.as_str())
581    }
582
583    pub fn rel_types(&self) -> impl Iterator<Item = &RelType> {
584        self.rel_types.iter()
585    }
586
587    pub fn get_or_create_table(&mut self, kind: TableKind, name: &str) -> TableId {
588        let key = (kind, name.to_string());
589        if let Some(id) = self.tables_by_key.get(&key) {
590            return *id;
591        }
592        let id = TableId(self.tables.len() as u32);
593        self.tables.push(TableDescriptor {
594            id,
595            name: name.to_string(),
596            kind,
597            state: SchemaObjectState::Public,
598        });
599        self.tables_by_key.insert(key, id);
600        id
601    }
602
603    pub fn table_id(&self, kind: TableKind, name: &str) -> Option<TableId> {
604        self.tables_by_key.get(&(kind, name.to_string())).copied()
605    }
606
607    pub fn table_descriptor(&self, id: TableId) -> Option<&TableDescriptor> {
608        self.tables
609            .get(id.0 as usize)
610            .filter(|table| !table.name.is_empty())
611    }
612
613    pub fn set_table_state(&mut self, id: TableId, state: SchemaObjectState) -> bool {
614        let Some(table) = self.tables.get_mut(id.0 as usize) else {
615            return false;
616        };
617        if table.name.is_empty() {
618            return false;
619        }
620        table.state = state;
621        true
622    }
623
624    pub fn remove_table_descriptor(&mut self, id: TableId) -> bool {
625        let Some(table) = self.tables.get_mut(id.0 as usize) else {
626            return false;
627        };
628        if table.name.is_empty() {
629            return false;
630        }
631        let key = (table.kind, table.name.clone());
632        table.name.clear();
633        self.tables_by_key.remove(&key);
634
635        let property_ids = self
636            .properties
637            .iter()
638            .filter(|property| property.table_id == id && !property.name.is_empty())
639            .map(|property| property.id)
640            .collect::<Vec<_>>();
641        for property_id in property_ids {
642            self.remove_property_descriptor(property_id);
643        }
644        true
645    }
646
647    pub fn import_table(
648        &mut self,
649        id: TableId,
650        kind: TableKind,
651        name: String,
652        state: SchemaObjectState,
653    ) {
654        let index = id.0 as usize;
655        while self.tables.len() <= index {
656            let next = TableId(self.tables.len() as u32);
657            self.tables.push(TableDescriptor {
658                id: next,
659                name: String::new(),
660                kind: TableKind::Node,
661                state: SchemaObjectState::Public,
662            });
663        }
664        self.tables[index] = TableDescriptor {
665            id,
666            name: name.clone(),
667            kind,
668            state,
669        };
670        self.tables_by_key.insert((kind, name), id);
671    }
672
673    pub fn table_descriptors(&self) -> impl Iterator<Item = &TableDescriptor> {
674        self.tables.iter().filter(|table| !table.name.is_empty())
675    }
676
677    pub fn get_or_create_property(
678        &mut self,
679        table_id: TableId,
680        name: &str,
681        value_type: PropertyType,
682        nullable: bool,
683    ) -> PropertyId {
684        self.get_or_create_property_with_default(
685            table_id,
686            name,
687            value_type,
688            nullable,
689            None,
690            SchemaObjectState::Public,
691        )
692    }
693
694    /// Creates a descriptor with an optional creation-time default in the
695    /// given initial state, or returns the existing descriptor unchanged.
696    pub fn get_or_create_property_with_default(
697        &mut self,
698        table_id: TableId,
699        name: &str,
700        value_type: PropertyType,
701        nullable: bool,
702        default: Option<DeclaredPropertyDefault>,
703        state: SchemaObjectState,
704    ) -> PropertyId {
705        let key = (table_id, name.to_string());
706        if let Some(id) = self.properties_by_key.get(&key) {
707            return *id;
708        }
709        let id = PropertyId(self.properties.len() as u32);
710        self.properties.push(PropertyDescriptor {
711            id,
712            table_id,
713            name: name.to_string(),
714            value_type,
715            nullable,
716            state,
717            default,
718        });
719        self.properties_by_key.insert(key, id);
720        id
721    }
722
723    pub fn property_descriptor_id(&self, table_id: TableId, name: &str) -> Option<PropertyId> {
724        self.properties_by_key
725            .get(&(table_id, name.to_string()))
726            .copied()
727    }
728
729    pub fn import_property_descriptor(
730        &mut self,
731        id: PropertyId,
732        table_id: TableId,
733        name: String,
734        value_type: PropertyType,
735        nullable: bool,
736        state: SchemaObjectState,
737    ) {
738        let index = id.0 as usize;
739        while self.properties.len() <= index {
740            let next = PropertyId(self.properties.len() as u32);
741            self.properties.push(PropertyDescriptor {
742                id: next,
743                table_id: TableId(0),
744                name: String::new(),
745                value_type: PropertyType::Any,
746                nullable: true,
747                state: SchemaObjectState::Public,
748                default: None,
749            });
750        }
751        self.properties[index] = PropertyDescriptor {
752            id,
753            table_id,
754            name: name.clone(),
755            value_type,
756            nullable,
757            state,
758            default: None,
759        };
760        self.properties_by_key.insert((table_id, name), id);
761    }
762
763    pub fn property_descriptors(&self) -> impl Iterator<Item = &PropertyDescriptor> {
764        self.properties
765            .iter()
766            .filter(|property| !property.name.is_empty())
767    }
768
769    /// Borrows one table's live descriptors in property-name order.
770    ///
771    /// The existing key map bounds the visit to this table; callers can apply
772    /// a small inspection limit without scanning unrelated schema objects.
773    pub fn table_property_descriptors(
774        &self,
775        table_id: TableId,
776    ) -> impl Iterator<Item = &PropertyDescriptor> {
777        self.properties_by_key
778            .range((table_id, String::new())..)
779            .take_while(move |((candidate, _), _)| *candidate == table_id)
780            .filter_map(|(_, id)| self.property_descriptor(*id))
781    }
782
783    pub fn property_descriptor(&self, id: PropertyId) -> Option<&PropertyDescriptor> {
784        self.properties
785            .get(id.0 as usize)
786            .filter(|property| !property.name.is_empty())
787    }
788
789    /// Restores a persisted default on an imported descriptor.
790    pub fn set_property_default(
791        &mut self,
792        id: PropertyId,
793        default: Option<DeclaredPropertyDefault>,
794    ) -> bool {
795        let Some(property) = self.properties.get_mut(id.0 as usize) else {
796            return false;
797        };
798        if property.name.is_empty() {
799            return false;
800        }
801        property.default = default;
802        true
803    }
804
805    /// Every live property descriptor with its table, ordered by table kind,
806    /// table name and property name.
807    pub fn property_schemas(&self) -> Vec<PropertySchema> {
808        let mut schemas = self
809            .property_descriptors()
810            .filter_map(|property| {
811                let table = self.table_descriptor(property.table_id)?;
812                Some(PropertySchema {
813                    table_kind: table.kind,
814                    table: table.name.clone(),
815                    property: property.name.clone(),
816                    value_type: property.value_type,
817                    nullable: property.nullable,
818                    state: property.state,
819                    default: property.default.clone(),
820                })
821            })
822            .collect::<Vec<_>>();
823        schemas.sort_by(|left, right| {
824            (left.table_kind, &left.table, &left.property).cmp(&(
825                right.table_kind,
826                &right.table,
827                &right.property,
828            ))
829        });
830        schemas
831    }
832
833    /// Whether any live descriptor declares a default.
834    pub fn has_property_defaults(&self) -> bool {
835        self.property_descriptors()
836            .any(|property| property.default.is_some())
837    }
838
839    /// Defaults to apply to a record of `kind` table `name` created now:
840    /// descriptors whose state admits writes and that declare a default.
841    pub fn creation_defaults(
842        &self,
843        kind: TableKind,
844        name: &str,
845    ) -> impl Iterator<Item = (&str, &PropertyDefault)> {
846        self.table_id(kind, name)
847            .into_iter()
848            .flat_map(move |table_id| self.table_property_descriptors(table_id))
849            .filter(|property| PropertyDefault::applies_in(property.state))
850            .filter_map(|property| {
851                property
852                    .default
853                    .as_ref()
854                    .map(|default| (property.name.as_str(), &default.value))
855            })
856    }
857
858    /// Inserts every applicable default whose key is absent from
859    /// `properties`. Present keys, including explicit NULLs, are kept.
860    pub fn fill_creation_defaults(
861        &self,
862        kind: TableKind,
863        name: &str,
864        properties: &mut BTreeMap<String, Value>,
865        clock: &mut impl FnMut() -> crate::temporal::PlainDateTime,
866    ) {
867        for (property, default) in self.creation_defaults(kind, name) {
868            if !properties.contains_key(property) {
869                properties.insert(property.to_string(), default.resolve(clock()));
870            }
871        }
872    }
873
874    pub fn set_property_state(&mut self, id: PropertyId, state: SchemaObjectState) -> bool {
875        let Some(property) = self.properties.get_mut(id.0 as usize) else {
876            return false;
877        };
878        if property.name.is_empty() {
879            return false;
880        }
881        property.state = state;
882        true
883    }
884
885    pub fn remove_property_descriptor(&mut self, id: PropertyId) -> bool {
886        let Some(property) = self.properties.get_mut(id.0 as usize) else {
887            return false;
888        };
889        if property.name.is_empty() {
890            return false;
891        }
892        let key = (property.table_id, property.name.clone());
893        property.name.clear();
894        self.properties_by_key.remove(&key);
895        true
896    }
897
898    pub fn get_or_create_property_index(&mut self, label_id: LabelId, property: &str) -> IndexId {
899        self.get_or_create_property_index_with_kind(label_id, property, IndexKind::Equality)
900    }
901
902    pub fn get_or_create_property_index_with_kind(
903        &mut self,
904        label_id: LabelId,
905        property: &str,
906        kind: IndexKind,
907    ) -> IndexId {
908        let key = (label_id, property.to_string());
909        let key = (key.0, key.1, kind);
910        if let Some(id) = self.property_indexes_by_key.get(&key) {
911            return *id;
912        }
913        let id = self.next_index_id();
914        self.property_indexes.push(IndexDescriptor {
915            id,
916            label_id,
917            property: property.to_string(),
918            kind,
919        });
920        self.property_indexes_by_key.insert(key, id);
921        id
922    }
923
924    pub fn property_index_id(&self, label_id: LabelId, property: &str) -> Option<IndexId> {
925        self.property_index_id_with_kind(label_id, property, IndexKind::Equality)
926    }
927
928    pub fn property_index_id_with_kind(
929        &self,
930        label_id: LabelId,
931        property: &str,
932        kind: IndexKind,
933    ) -> Option<IndexId> {
934        self.property_indexes_by_key
935            .get(&(label_id, property.to_string(), kind))
936            .copied()
937    }
938
939    pub fn import_property_index(&mut self, id: IndexId, label_id: LabelId, property: String) {
940        self.import_property_index_with_kind(id, label_id, property, IndexKind::Equality);
941    }
942
943    pub fn import_property_index_with_kind(
944        &mut self,
945        id: IndexId,
946        label_id: LabelId,
947        property: String,
948        kind: IndexKind,
949    ) {
950        let index = id.0 as usize;
951        while self.property_indexes.len() <= index {
952            let next = IndexId(self.property_indexes.len() as u32);
953            self.property_indexes.push(IndexDescriptor {
954                id: next,
955                label_id: LabelId(0),
956                property: String::new(),
957                kind: IndexKind::Equality,
958            });
959        }
960        self.property_indexes[index] = IndexDescriptor {
961            id,
962            label_id,
963            property: property.clone(),
964            kind,
965        };
966        self.property_indexes_by_key
967            .insert((label_id, property, kind), id);
968    }
969
970    pub fn property_indexes(&self) -> impl Iterator<Item = &IndexDescriptor> {
971        self.property_indexes
972            .iter()
973            .filter(|index| !index.property.is_empty())
974    }
975
976    pub fn property_index_descriptor(&self, id: IndexId) -> Option<&IndexDescriptor> {
977        self.property_indexes().find(|index| index.id == id)
978    }
979
980    pub fn get_or_create_composite_property_index(
981        &mut self,
982        label_id: LabelId,
983        properties: &[String],
984    ) -> IndexId {
985        let key = (label_id, properties.to_vec());
986        if let Some(id) = self.composite_property_indexes_by_key.get(&key) {
987            return *id;
988        }
989        let id = self.next_index_id();
990        self.composite_property_indexes
991            .push(CompositeIndexDescriptor {
992                id,
993                label_id,
994                properties: properties.to_vec(),
995            });
996        self.composite_property_indexes_by_key.insert(key, id);
997        id
998    }
999
1000    pub fn composite_property_index_id(
1001        &self,
1002        label_id: LabelId,
1003        properties: &[String],
1004    ) -> Option<IndexId> {
1005        self.composite_property_indexes_by_key
1006            .get(&(label_id, properties.to_vec()))
1007            .copied()
1008    }
1009
1010    pub fn import_composite_property_index(
1011        &mut self,
1012        id: IndexId,
1013        label_id: LabelId,
1014        properties: Vec<String>,
1015    ) {
1016        self.composite_property_indexes
1017            .push(CompositeIndexDescriptor {
1018                id,
1019                label_id,
1020                properties: properties.clone(),
1021            });
1022        self.composite_property_indexes_by_key
1023            .insert((label_id, properties), id);
1024    }
1025
1026    pub fn composite_property_indexes(&self) -> impl Iterator<Item = &CompositeIndexDescriptor> {
1027        self.composite_property_indexes
1028            .iter()
1029            .filter(|index| !index.properties.is_empty())
1030    }
1031
1032    pub fn composite_property_index_descriptor(
1033        &self,
1034        id: IndexId,
1035    ) -> Option<&CompositeIndexDescriptor> {
1036        self.composite_property_indexes()
1037            .find(|index| index.id == id)
1038    }
1039
1040    pub fn has_scalar_property_index(&self, label_id: LabelId, property: &str) -> bool {
1041        [IndexKind::Equality, IndexKind::Range]
1042            .into_iter()
1043            .any(|kind| {
1044                self.property_index_id_with_kind(label_id, property, kind)
1045                    .is_some()
1046            })
1047    }
1048
1049    pub fn supports_index_statistics(&self, id: IndexId) -> bool {
1050        match (
1051            self.property_index_descriptor(id),
1052            self.composite_property_index_descriptor(id),
1053        ) {
1054            (Some(index), None) => index.kind != IndexKind::FullText,
1055            (None, Some(_)) => true,
1056            _ => false,
1057        }
1058    }
1059
1060    fn next_index_id(&self) -> IndexId {
1061        let next = self
1062            .property_indexes()
1063            .map(|index| index.id.0)
1064            .chain(self.composite_property_indexes().map(|index| index.id.0))
1065            .max()
1066            .map_or(0, |id| {
1067                id.checked_add(1)
1068                    .expect("schema index identifier space is exhausted")
1069            });
1070        IndexId(next)
1071    }
1072
1073    pub fn get_or_create_unique_constraint(
1074        &mut self,
1075        label_id: LabelId,
1076        property: &str,
1077    ) -> ConstraintId {
1078        self.get_or_create_constraint(
1079            ConstraintSubject::Node(label_id),
1080            property,
1081            ConstraintKind::NodePropertyUnique,
1082        )
1083    }
1084
1085    pub fn unique_constraint_id(&self, label_id: LabelId, property: &str) -> Option<ConstraintId> {
1086        self.constraint_id(
1087            ConstraintSubject::Node(label_id),
1088            property,
1089            ConstraintKind::NodePropertyUnique,
1090        )
1091    }
1092
1093    pub fn get_or_create_node_property_exists_constraint(
1094        &mut self,
1095        label_id: LabelId,
1096        property: &str,
1097    ) -> ConstraintId {
1098        self.get_or_create_constraint(
1099            ConstraintSubject::Node(label_id),
1100            property,
1101            ConstraintKind::NodePropertyExists,
1102        )
1103    }
1104
1105    pub fn node_property_exists_constraint_id(
1106        &self,
1107        label_id: LabelId,
1108        property: &str,
1109    ) -> Option<ConstraintId> {
1110        self.constraint_id(
1111            ConstraintSubject::Node(label_id),
1112            property,
1113            ConstraintKind::NodePropertyExists,
1114        )
1115    }
1116
1117    pub fn get_or_create_relationship_property_exists_constraint(
1118        &mut self,
1119        rel_type_id: RelTypeId,
1120        property: &str,
1121    ) -> ConstraintId {
1122        self.get_or_create_constraint(
1123            ConstraintSubject::Relationship(rel_type_id),
1124            property,
1125            ConstraintKind::RelationshipPropertyExists,
1126        )
1127    }
1128
1129    pub fn relationship_property_exists_constraint_id(
1130        &self,
1131        rel_type_id: RelTypeId,
1132        property: &str,
1133    ) -> Option<ConstraintId> {
1134        self.constraint_id(
1135            ConstraintSubject::Relationship(rel_type_id),
1136            property,
1137            ConstraintKind::RelationshipPropertyExists,
1138        )
1139    }
1140
1141    pub fn get_or_create_relationship_unique_constraint(
1142        &mut self,
1143        rel_type_id: RelTypeId,
1144        property: &str,
1145    ) -> ConstraintId {
1146        self.get_or_create_constraint(
1147            ConstraintSubject::Relationship(rel_type_id),
1148            property,
1149            ConstraintKind::RelationshipPropertyUnique,
1150        )
1151    }
1152
1153    pub fn relationship_unique_constraint_id(
1154        &self,
1155        rel_type_id: RelTypeId,
1156        property: &str,
1157    ) -> Option<ConstraintId> {
1158        self.constraint_id(
1159            ConstraintSubject::Relationship(rel_type_id),
1160            property,
1161            ConstraintKind::RelationshipPropertyUnique,
1162        )
1163    }
1164
1165    pub fn import_unique_constraint(
1166        &mut self,
1167        id: ConstraintId,
1168        label_id: LabelId,
1169        property: String,
1170    ) {
1171        self.import_constraint(
1172            id,
1173            ConstraintSubject::Node(label_id),
1174            property,
1175            ConstraintKind::NodePropertyUnique,
1176        );
1177    }
1178
1179    pub fn import_node_property_exists_constraint(
1180        &mut self,
1181        id: ConstraintId,
1182        label_id: LabelId,
1183        property: String,
1184    ) {
1185        self.import_constraint(
1186            id,
1187            ConstraintSubject::Node(label_id),
1188            property,
1189            ConstraintKind::NodePropertyExists,
1190        );
1191    }
1192
1193    pub fn import_relationship_property_exists_constraint(
1194        &mut self,
1195        id: ConstraintId,
1196        rel_type_id: RelTypeId,
1197        property: String,
1198    ) {
1199        self.import_constraint(
1200            id,
1201            ConstraintSubject::Relationship(rel_type_id),
1202            property,
1203            ConstraintKind::RelationshipPropertyExists,
1204        );
1205    }
1206
1207    pub fn import_relationship_unique_constraint(
1208        &mut self,
1209        id: ConstraintId,
1210        rel_type_id: RelTypeId,
1211        property: String,
1212    ) {
1213        self.import_constraint(
1214            id,
1215            ConstraintSubject::Relationship(rel_type_id),
1216            property,
1217            ConstraintKind::RelationshipPropertyUnique,
1218        );
1219    }
1220
1221    fn get_or_create_constraint(
1222        &mut self,
1223        subject: ConstraintSubject,
1224        property: &str,
1225        kind: ConstraintKind,
1226    ) -> ConstraintId {
1227        let key = (subject, property.to_string(), kind);
1228        if let Some(id) = self.constraints_by_key.get(&key) {
1229            return *id;
1230        }
1231        let id = ConstraintId(self.constraints.len() as u32);
1232        self.constraints.push(ConstraintDescriptor {
1233            id,
1234            subject,
1235            property: property.to_string(),
1236            kind,
1237        });
1238        self.constraints_by_key.insert(key, id);
1239        id
1240    }
1241
1242    fn constraint_id(
1243        &self,
1244        subject: ConstraintSubject,
1245        property: &str,
1246        kind: ConstraintKind,
1247    ) -> Option<ConstraintId> {
1248        self.constraints_by_key
1249            .get(&(subject, property.to_string(), kind))
1250            .copied()
1251    }
1252
1253    fn import_constraint(
1254        &mut self,
1255        id: ConstraintId,
1256        subject: ConstraintSubject,
1257        property: String,
1258        kind: ConstraintKind,
1259    ) {
1260        let index = id.0 as usize;
1261        while self.constraints.len() <= index {
1262            let next = ConstraintId(self.constraints.len() as u32);
1263            self.constraints.push(ConstraintDescriptor {
1264                id: next,
1265                subject,
1266                property: String::new(),
1267                kind,
1268            });
1269        }
1270        self.constraints[index] = ConstraintDescriptor {
1271            id,
1272            subject,
1273            property: property.clone(),
1274            kind,
1275        };
1276        self.constraints_by_key
1277            .insert((subject, property, kind), id);
1278    }
1279
1280    pub fn unique_constraints(&self) -> impl Iterator<Item = &ConstraintDescriptor> {
1281        self.constraints.iter().filter(|constraint| {
1282            !constraint.property.is_empty() && constraint.kind == ConstraintKind::NodePropertyUnique
1283        })
1284    }
1285
1286    pub fn node_property_exists_constraints(&self) -> impl Iterator<Item = &ConstraintDescriptor> {
1287        self.constraints.iter().filter(|constraint| {
1288            !constraint.property.is_empty() && constraint.kind == ConstraintKind::NodePropertyExists
1289        })
1290    }
1291
1292    pub fn relationship_property_exists_constraints(
1293        &self,
1294    ) -> impl Iterator<Item = &ConstraintDescriptor> {
1295        self.constraints.iter().filter(|constraint| {
1296            !constraint.property.is_empty()
1297                && constraint.kind == ConstraintKind::RelationshipPropertyExists
1298        })
1299    }
1300
1301    pub fn relationship_unique_constraints(&self) -> impl Iterator<Item = &ConstraintDescriptor> {
1302        self.constraints.iter().filter(|constraint| {
1303            !constraint.property.is_empty()
1304                && constraint.kind == ConstraintKind::RelationshipPropertyUnique
1305        })
1306    }
1307
1308    pub fn import_label(&mut self, id: LabelId, name: String) {
1309        let index = id.0 as usize;
1310        while self.labels.len() <= index {
1311            let next = LabelId(self.labels.len() as u32);
1312            self.labels.push(Arc::new(Label {
1313                id: next,
1314                name: String::new(),
1315            }));
1316        }
1317        let previous = self.labels[index].name.as_str();
1318        if self.labels_by_name.get(previous).copied() == Some(id) {
1319            self.labels_by_name.remove(previous);
1320        }
1321        self.labels_by_name.remove(name.as_str());
1322        let label = Arc::new(Label { id, name });
1323        self.labels_by_name
1324            .insert(LabelNameKey(Arc::clone(&label)), id);
1325        self.labels[index] = label;
1326    }
1327
1328    pub fn import_rel_type(&mut self, id: RelTypeId, name: String) {
1329        let index = id.0 as usize;
1330        while self.rel_types.len() <= index {
1331            let next = RelTypeId(self.rel_types.len() as u32);
1332            self.rel_types.push(RelType {
1333                id: next,
1334                name: String::new(),
1335            });
1336        }
1337        self.rel_types[index] = RelType {
1338            id,
1339            name: name.clone(),
1340        };
1341        self.rel_types_by_name.insert(name, id);
1342    }
1343}
1344
1345#[cfg(test)]
1346mod tests {
1347    use super::*;
1348
1349    #[derive(Debug)]
1350    struct LabelAllocation {
1351        bytes: usize,
1352        source_on_release: Option<std::sync::Weak<Label>>,
1353    }
1354
1355    impl RetainedLabelAllocation for LabelAllocation {
1356        fn bytes(&self) -> usize {
1357            self.bytes
1358        }
1359    }
1360
1361    impl Drop for LabelAllocation {
1362        fn drop(&mut self) {
1363            if let Some(source) = &self.source_on_release {
1364                assert_eq!(source.strong_count(), 0, "symbol must drop before permit");
1365            }
1366        }
1367    }
1368
1369    #[test]
1370    fn retained_label_name_preserves_source_and_snapshot_without_catalog_pin() {
1371        let mut catalog = Catalog::default();
1372        let id = LabelId(0);
1373        let mut name = String::with_capacity(16 * 1024);
1374        name.push_str("original");
1375        catalog.import_label(id, name);
1376        let other = catalog.get_or_create_label("unrelated");
1377        let capacity = catalog.labels[id.0 as usize].name.capacity();
1378        let snapshot = catalog.clone();
1379        assert_eq!(
1380            snapshot.label_name(id).unwrap().as_ptr(),
1381            catalog.label_name(id).unwrap().as_ptr()
1382        );
1383        drop(snapshot);
1384        let original = Arc::downgrade(&catalog.labels[id.0 as usize]);
1385        let unrelated = Arc::downgrade(&catalog.labels[other.0 as usize]);
1386        let address = catalog.label_name(id).unwrap().as_ptr() as usize;
1387        let preflight = catalog
1388            .retained_label_name_capacity_bytes(id)
1389            .unwrap()
1390            .unwrap();
1391        let source = catalog
1392            .retain_label_name_with_admission(id, |bytes| -> crate::Result<_> {
1393                assert_eq!(original.strong_count(), 2);
1394                assert_eq!(bytes, preflight);
1395                assert!(
1396                    bytes
1397                        >= std::mem::size_of::<Label>()
1398                            + 2 * std::mem::size_of::<usize>()
1399                            + capacity
1400                );
1401                Ok(LabelAllocation {
1402                    bytes,
1403                    source_on_release: Some(original.clone()),
1404                })
1405            })
1406            .unwrap()
1407            .unwrap();
1408        catalog.import_label(id, "replacement".into());
1409        assert_eq!(catalog.label_name(id), Some("replacement"));
1410        assert_eq!(catalog.label_id("original"), None);
1411        assert_eq!(catalog.label_id("replacement"), Some(id));
1412        assert_eq!(
1413            original.strong_count(),
1414            1,
1415            "only the retained name survives"
1416        );
1417        drop(catalog);
1418        assert_eq!(unrelated.strong_count(), 0);
1419        assert_eq!(source.id(), id);
1420        assert_eq!(source.name(), "original");
1421        assert_eq!(source.name().as_ptr() as usize, address);
1422        drop(source);
1423        assert_eq!(original.strong_count(), 0);
1424    }
1425
1426    #[test]
1427    fn import_label_removes_only_its_own_previous_name_mapping() {
1428        let mut catalog = Catalog::default();
1429        let original = catalog.get_or_create_label("original");
1430        let snapshot = catalog.clone();
1431        catalog.import_label(original, "replacement".into());
1432        assert_eq!(catalog.label_id("original"), None);
1433        assert_eq!(snapshot.label_id("original"), Some(original));
1434        assert_eq!(snapshot.label_id("replacement"), None);
1435        let renamed = catalog.get_or_create_label("original");
1436        assert_ne!(renamed, original);
1437        catalog.import_label(original, "original".into());
1438        assert_eq!(catalog.label_id("original"), Some(original));
1439        catalog.import_label(renamed, "third".into());
1440        assert_eq!(catalog.label_id("original"), Some(original));
1441        assert_eq!(catalog.label_id("replacement"), None);
1442        assert_eq!(catalog.label_id("third"), Some(renamed));
1443    }
1444
1445    #[test]
1446    fn label_admission_refusal_and_missing_do_not_retain_source() {
1447        let mut catalog = Catalog::default();
1448        let id = catalog.get_or_create_label("Item");
1449        let source = &catalog.labels[id.0 as usize];
1450        let owners = Arc::strong_count(source);
1451        let result =
1452            catalog.retain_label_name_with_admission(id, |_| -> crate::Result<LabelAllocation> {
1453                assert_eq!(Arc::strong_count(source), owners);
1454                Err(crate::HawDBError::Execution(
1455                    "label admission sentinel".into(),
1456                ))
1457            });
1458        assert!(
1459            matches!(result, Err(crate::HawDBError::Execution(reason)) if reason == "label admission sentinel")
1460        );
1461        assert_eq!(Arc::strong_count(source), owners);
1462        let result = catalog.retain_label_name_with_admission(id, |_| -> crate::Result<_> {
1463            Ok(LabelAllocation {
1464                bytes: 0,
1465                source_on_release: None,
1466            })
1467        });
1468        assert!(
1469            matches!(result, Err(crate::HawDBError::Execution(reason)) if reason.contains("insufficient allocation permit"))
1470        );
1471        assert_eq!(Arc::strong_count(source), owners);
1472        assert!(catalog
1473            .retain_label_name_with_admission(
1474                LabelId(u32::MAX),
1475                |_| -> crate::Result<LabelAllocation> {
1476                    panic!("missing label must skip admission");
1477                }
1478            )
1479            .unwrap()
1480            .is_none());
1481    }
1482
1483    #[test]
1484    fn label_admission_preserves_typed_host_refusal() {
1485        #[derive(Debug)]
1486        enum HostError {
1487            Refused { retryable: bool, identity: Arc<()> },
1488            Storage(crate::HawDBError),
1489        }
1490        impl From<crate::HawDBError> for HostError {
1491            fn from(error: crate::HawDBError) -> Self {
1492                Self::Storage(error)
1493            }
1494        }
1495        let mut catalog = Catalog::default();
1496        let id = catalog.get_or_create_label("Item");
1497        for retryable in [true, false] {
1498            let identity = Arc::new(());
1499            let result = catalog.retain_label_name_with_admission(
1500                id,
1501                |_| -> std::result::Result<LabelAllocation, HostError> {
1502                    Err(HostError::Refused {
1503                        retryable,
1504                        identity: Arc::clone(&identity),
1505                    })
1506                },
1507            );
1508            match result {
1509                Err(HostError::Refused {
1510                    retryable: observed,
1511                    identity: observed_identity,
1512                }) => {
1513                    assert_eq!(observed, retryable);
1514                    assert!(Arc::ptr_eq(&identity, &observed_identity));
1515                }
1516                Err(HostError::Storage(error)) => panic!("host error was converted: {error}"),
1517                Ok(_) => panic!("host refusal was ignored"),
1518            }
1519            assert_eq!(Arc::strong_count(&catalog.labels[id.0 as usize]), 2);
1520        }
1521    }
1522
1523    #[test]
1524    fn label_directory_shares_names_and_preserves_borrowed_lookup_order() {
1525        let mut catalog = Catalog::default();
1526        for name in ["zeta", "alpha", "beta"] {
1527            let id = catalog.get_or_create_label(name);
1528            let (key, indexed_id) = catalog.labels_by_name.get_key_value(name).unwrap();
1529            assert_eq!(*indexed_id, id);
1530            assert!(Arc::ptr_eq(&key.0, &catalog.labels[id.0 as usize]));
1531        }
1532        assert_eq!(
1533            catalog
1534                .labels_by_name
1535                .keys()
1536                .map(|key| key.0.name.as_str())
1537                .collect::<Vec<_>>(),
1538            ["alpha", "beta", "zeta"]
1539        );
1540        let id = catalog.label_id("alpha").unwrap();
1541        catalog.import_label(id, "alpha".into());
1542        let (key, indexed_id) = catalog.labels_by_name.get_key_value("alpha").unwrap();
1543        assert_eq!(*indexed_id, id);
1544        assert!(Arc::ptr_eq(&key.0, &catalog.labels[id.0 as usize]));
1545        assert_eq!(catalog.get_or_create_label("alpha"), id);
1546    }
1547
1548    #[test]
1549    fn advanced_statistics_freshness_requires_complete_current_epoch_data() {
1550        let unavailable = GraphStatistics {
1551            computed_at_commit_epoch: 7,
1552            advanced_statistics_complete: false,
1553            ..GraphStatistics::default()
1554        };
1555        assert_eq!(
1556            unavailable.advanced_statistics_freshness(7),
1557            AdvancedStatisticsFreshness::Unavailable
1558        );
1559
1560        let complete = GraphStatistics {
1561            advanced_statistics_complete: true,
1562            ..unavailable
1563        };
1564        assert_eq!(
1565            complete.advanced_statistics_freshness(7),
1566            AdvancedStatisticsFreshness::Fresh
1567        );
1568        assert_eq!(
1569            complete.advanced_statistics_freshness(8),
1570            AdvancedStatisticsFreshness::Stale
1571        );
1572        assert_eq!(complete.advanced_statistics_commit_lag(9), 2);
1573    }
1574
1575    #[test]
1576    fn property_types_map_to_shared_logical_types() {
1577        assert_eq!(PropertyType::Bool.logical_type(), LogicalType::Boolean);
1578        assert_eq!(PropertyType::Int.logical_type(), LogicalType::Int64);
1579        assert_eq!(PropertyType::Float.logical_type(), LogicalType::Float64);
1580        assert_eq!(PropertyType::String.logical_type(), LogicalType::String);
1581        assert_eq!(PropertyType::Text.logical_type(), LogicalType::Text);
1582        assert_eq!(PropertyType::List.logical_type(), LogicalType::List);
1583        assert_eq!(PropertyType::Any.logical_type(), LogicalType::Any);
1584    }
1585
1586    #[test]
1587    fn index_identifiers_are_unique_across_descriptor_kinds() {
1588        let mut catalog = Catalog::default();
1589        let label = catalog.get_or_create_label("Memory");
1590        let composite = catalog.get_or_create_composite_property_index(
1591            label,
1592            &["space_id".to_string(), "external_id".to_string()],
1593        );
1594        let equality = catalog.get_or_create_property_index(label, "id");
1595        let range =
1596            catalog.get_or_create_property_index_with_kind(label, "created_at", IndexKind::Range);
1597
1598        assert_ne!(composite, equality);
1599        assert_ne!(composite, range);
1600        assert_ne!(equality, range);
1601    }
1602
1603    #[test]
1604    fn imported_identifier_collision_disables_ambiguous_statistics() {
1605        let mut catalog = Catalog::default();
1606        let label = catalog.get_or_create_label("Memory");
1607        let id = catalog.get_or_create_property_index(label, "id");
1608        catalog.import_composite_property_index(
1609            id,
1610            label,
1611            vec!["space_id".to_string(), "external_id".to_string()],
1612        );
1613
1614        assert!(!catalog.supports_index_statistics(id));
1615    }
1616
1617    #[test]
1618    fn index_sample_estimate_is_bounded_and_rejects_stale_churn() {
1619        let sampled = IndexStatisticsSample {
1620            index_size: 1_000,
1621            unique_values: 40,
1622            sample_size: 100,
1623            updates_since_sample: 50,
1624        };
1625        assert_eq!(sampled.estimated_unique_values(), Some(400));
1626
1627        let stale = IndexStatisticsSample {
1628            updates_since_sample: 51,
1629            ..sampled
1630        };
1631        assert!(stale.is_stale());
1632        assert_eq!(stale.estimated_unique_values(), None);
1633
1634        let invalid = IndexStatisticsSample {
1635            index_size: 10,
1636            unique_values: 11,
1637            sample_size: 10,
1638            updates_since_sample: 0,
1639        };
1640        assert!(!invalid.is_valid());
1641        assert_eq!(invalid.estimated_unique_values(), None);
1642    }
1643}