Skip to main content

relate_executor/graph/
theater.rs

1//! Committed SHOW metadata captured with a checkpoint, plus the read-admission
2//! schema snapshot derived from it.
3
4use std::collections::BTreeMap;
5use std::sync::Mutex;
6
7use relate_catalog::Catalog;
8#[cfg(test)]
9use relate_catalog::ConstraintDef;
10use relate_core::{Error, Namespace, Result};
11
12use crate::redo::{self, RedoOp};
13
14use super::{matching_enforced_label, requires_enforced_label, Graph};
15
16pub use relate_engine_api::{
17    map_put_database, CheckpointTheater, DatabaseEntry, SchemaSnapshot, ShowSchema, TheaterData,
18};
19
20/// invariants): the three fixed
21/// namespaces' settings (default language, composite flag) live in ONE
22/// table shared by every namespace graph of the store through the
23/// `StoreServices` bundle. `ALTER DATABASE` writes it and `SHOW DATABASES`
24/// reads it from any namespace session, so the two can never diverge the
25/// way per-graph theater copies did. The table is keyed by `Namespace`, so
26/// it holds exactly the three fixed entries by construction and every
27/// lookup is total; the on-disk checkpoint theater image keeps serializing
28/// it as strings under its historical `databases` key, with the boundary
29/// conversion in [`Self::sanitize`] and [`Graph::checkpoint_theater`].
30#[derive(Debug)]
31pub(crate) struct DatabasesCatalog {
32    entries: Mutex<BTreeMap<Namespace, DatabaseEntry>>,
33}
34
35impl DatabasesCatalog {
36    /// ADR-0116 §1/§8: a fixed namespace's default entry — `CYPHER 25`,
37    /// non-composite — until an `ALTER DATABASE ... SET DEFAULT LANGUAGE`
38    /// redo says otherwise. `Default` and [`Self::sanitize`] seed every
39    /// fixed namespace with it, and the typed key plus filtered inserts
40    /// keep exactly the three entries present.
41    pub(crate) const DEFAULT_DATABASE_ENTRY: DatabaseEntry = DatabaseEntry {
42        default_language: 25,
43        composite: false,
44    };
45
46    /// The seeded table: exactly the three fixed namespaces, each at its
47    /// default entry.
48    fn seeded() -> BTreeMap<Namespace, DatabaseEntry> {
49        Namespace::ALL
50            .iter()
51            .map(|ns| (*ns, Self::DEFAULT_DATABASE_ENTRY))
52            .collect()
53    }
54
55    /// The committed table at one capture point (read admission or
56    /// checkpoint cut).
57    pub(crate) fn snapshot(&self) -> BTreeMap<Namespace, DatabaseEntry> {
58        self.entries.lock().unwrap().clone()
59    }
60
61    /// ADR-0116 §8: record a namespace's default language (committed redo
62    /// path; see `map_put_database` for the matching rule).
63    pub(crate) fn put_database(&self, name: &str, language: u32, composite: bool) {
64        map_put_database(&mut self.entries.lock().unwrap(), name, language, composite);
65    }
66
67    /// ADR-0116 §8: the boundary conversion for a checkpoint image's
68    /// string-keyed table. Entries for non-fixed names (from an older
69    /// store's `CREATE DATABASE` theater) are dropped so the next
70    /// checkpoint no longer carries them; names match case-insensitively,
71    /// and a fixed namespace missing from the image gets its default
72    /// (`CYPHER 25`).
73    pub(crate) fn sanitize(
74        map: &BTreeMap<String, DatabaseEntry>,
75    ) -> BTreeMap<Namespace, DatabaseEntry> {
76        // One matching rule (`Namespace::parse`, as in `map_put_database`):
77        // fold the image's entries over the seeded defaults, keeping only
78        // the fixed namespaces.
79        let mut out = Self::seeded();
80        for (name, entry) in map {
81            if let Some(ns) = Namespace::parse(name) {
82                out.insert(ns, *entry);
83            }
84        }
85        out
86    }
87
88    /// Install a checkpoint image's (already sanitized) table as the
89    /// store-level catalog.
90    pub(crate) fn install(&self, map: BTreeMap<Namespace, DatabaseEntry>) {
91        *self.entries.lock().unwrap() = map;
92    }
93}
94
95impl Default for DatabasesCatalog {
96    fn default() -> Self {
97        Self {
98            entries: Mutex::new(Self::seeded()),
99        }
100    }
101}
102
103/// Apply speculative catalog operations to this private admitted copy.
104pub(crate) fn apply_show_overlay<'o>(
105    show: &mut ShowSchema,
106    ops: impl IntoIterator<Item = &'o RedoOp>,
107) -> Result<()> {
108    for op in ops {
109        match op {
110            RedoOp::CatalogIndexDetail {
111                name,
112                detail,
113                options,
114            } => {
115                let options = redo::props_from_json(options)?;
116                show.data.index_details.insert(name.clone(), detail.clone());
117                show.data.index_options.insert(name.clone(), options);
118            }
119            RedoOp::DropIndex { name } => {
120                show.data.index_details.remove(name);
121                show.data.index_options.remove(name);
122            }
123            RedoOp::PutDatabase {
124                name,
125                language,
126                composite,
127            } => {
128                map_put_database(&mut show.databases, name, *language, *composite);
129            }
130            RedoOp::DropDatabase { .. } => {}
131            RedoOp::PutGraphType { name, body } => {
132                show.data.graph_types.insert(name.clone(), body.clone());
133            }
134            RedoOp::SetCurrentGraphType { body } => {
135                set_current_graph_type(&mut show.data, body)?;
136            }
137            RedoOp::CatalogDerivedConstraint { constraint } => {
138                show.data
139                    .derived_constraints
140                    .insert(constraint.name.clone(), constraint.clone());
141            }
142            RedoOp::DropConstraint { name } => {
143                show.data.derived_constraints.remove(name);
144            }
145            _ => {}
146        }
147    }
148    Ok(())
149}
150
151/// Install `spec` as the current graph type and re-derive its constraint index.
152pub(crate) fn set_current_graph_type(
153    data: &mut TheaterData,
154    spec: &crate::graph_type::GraphTypeSpec,
155) -> Result<()> {
156    let derived = crate::graph_type::derived_constraints_map(&spec.to_body())
157        .map_err(crate::graph_type::persisted_derive_error)?;
158    data.current_graph_type = spec.clone();
159    data.derived_constraints = derived;
160    Ok(())
161}
162
163impl Graph {
164    /// Capture the committed checkpoint metadata at the caller's checkpoint cut.
165    #[doc(hidden)]
166    pub fn checkpoint_theater(&self) -> CheckpointTheater {
167        CheckpointTheater {
168            // The on-disk image keeps the historical string keys; the
169            // in-memory table is `Namespace`-keyed.
170            databases: self
171                .databases()
172                .snapshot()
173                .into_iter()
174                .map(|(ns, entry)| (ns.as_str().to_string(), entry))
175                .collect(),
176            data: self.theater.lock().unwrap().clone(),
177            legacy_unknown_constraints: self
178                .legacy_unenforced
179                .lock()
180                .unwrap()
181                .clone()
182                .into_iter()
183                .collect(),
184        }
185    }
186
187    /// Validate a typed checkpoint image against its named catalog before
188    /// installing it; a missing enforced label must never relax a constraint.
189    ///
190    /// The graph type's derived-constraint index is a pure function of the
191    /// persisted spec, so the image is re-derived before the identity checks
192    /// run and the catalog's derived rows are re-keyed to match
193    /// ([`super::derived_migration::rederive_derived_constraints`]): a store
194    /// written before a naming or derivation change keeps loading instead of
195    /// failing on names its own binary no longer generates. The migration
196    /// runs on a copy of the catalog, so a rejected image leaves the graph
197    /// untouched.
198    #[doc(hidden)]
199    pub fn restore_checkpoint_theater(&self, image: CheckpointTheater) -> Result<()> {
200        let mut image = image;
201        {
202            let mut catalog = self.catalog.lock().unwrap();
203            let mut migrated = catalog.clone();
204            super::derived_migration::rederive_derived_constraints(&mut image.data, &mut migrated)?;
205            Self::validate_checkpoint_theater_image_in(&image, &migrated)?;
206            *catalog = migrated;
207        }
208        self.install_checkpoint_theater_image(image)
209    }
210
211    /// CIP-176 spec string for the JSON snapshot codec (ADR-0050). A
212    /// deserialized default value the canonical renderer cannot render is
213    /// the storage-corruption error family the checkpoint path uses for
214    /// the same persisted bytes (typed, never a panic).
215    pub fn graph_type_spec(&self) -> Result<Option<String>> {
216        let model = self.theater.lock().unwrap().current_graph_type.clone();
217        if model == Default::default() {
218            return Ok(None);
219        }
220        crate::graph_type::canonicalize_graph_type_body(&model.to_body())
221            .map_err(crate::graph_type::persisted_derive_error)
222            .map(Some)
223    }
224
225    /// Restore a Relate GraphData `graph_type` spec after snapshot load.
226    pub fn restore_graph_type_spec(&self, spec: Option<&str>) -> Result<()> {
227        let Some(raw) = spec.map(str::trim).filter(|s| !s.is_empty()) else {
228            return Ok(());
229        };
230        let inner = raw
231            .strip_prefix('{')
232            .and_then(|s| s.strip_suffix('}'))
233            .unwrap_or(raw);
234        let body = relate_parser::parse_graph_type_body(inner)
235            .map_err(|e| Error::storage(format!("invalid graph_type spec: {e}")))?;
236        // Install without re-validation, exactly as WAL replay and
237        // db.ontology.apply do (ADR-0388): the store's preview set is not
238        // resolved yet at load time (configure_preview runs after), so a
239        // gated construct a legitimately gated-opened store wrote must
240        // restore unchanged. Poisoned bytes still fail typed here: the
241        // derivation below renders every default it stores (the family's
242        // persisted message, round 8's rust Medium fix).
243        let spec = crate::graph_type::GraphTypeSpec::from_body(&body)
244            .map_err(crate::graph_type::persisted_validation_error)?;
245        let mut theater = self.theater.lock().unwrap();
246        set_current_graph_type(&mut theater, &spec)?;
247        Ok(())
248    }
249
250    /// Produce a validated typed image, preserving exact legacy-unknown
251    /// definitions alongside all known committed theater metadata.
252    #[doc(hidden)]
253    pub fn checkpoint_theater_for_write(&self) -> Result<CheckpointTheater> {
254        let image = self.checkpoint_theater();
255        self.validate_checkpoint_theater_image(&image)?;
256        Ok(image)
257    }
258
259    /// Record historical missing enforcement only after loading an untyped source.
260    #[doc(hidden)]
261    pub fn mark_legacy_unenforced(&self) {
262        let image = self.checkpoint_theater();
263        let catalog = self.catalog.lock().unwrap();
264        let mut legacy = self.legacy_unenforced.lock().unwrap();
265        for def in catalog
266            .constraints
267            .values()
268            .filter(|d| requires_enforced_label(d))
269        {
270            if !image
271                .data
272                .derived_constraints
273                .get(&def.name)
274                .is_some_and(|c| matching_enforced_label(def, c))
275            {
276                legacy.insert(def.name.clone(), def.clone());
277            }
278        }
279    }
280
281    /// Install an already-validated theater image (the typed image's checks,
282    /// or the legacy path's per-entry checks).
283    fn install_checkpoint_theater_image(&self, image: CheckpointTheater) -> Result<()> {
284        *self.legacy_unenforced.lock().unwrap() = image
285            .legacy_unknown_constraints
286            .iter()
287            .map(|(name, def)| (name.clone(), def.clone()))
288            .collect();
289        // ADR-0116 §8: an older store's image may carry `CREATE
290        // DATABASE` theater rows; the boundary conversion keeps only the
291        // fixed namespaces so the next checkpoint image no longer
292        // contains them.
293        let databases = DatabasesCatalog::sanitize(&image.databases);
294        // ADR-0276: the databases table is store-level — install it
295        // into the shared catalog every namespace graph reads.
296        self.databases().install(databases);
297        // Checkpoint rows feed only data labels and types; the DDL names live
298        // in this theater image. Record them through the same catalog sets so
299        // a name that existed only in an index or constraint survives a
300        // restart exactly as it did before one (ADR-0363 decision 5).
301        for detail in image.data.index_details.values() {
302            self.record_schema_names(detail.relationship, detail.labels.iter().cloned());
303        }
304        for constraint in image.data.derived_constraints.values() {
305            if let Some(enforced) = &constraint.enforced_label {
306                self.record_schema_names(false, std::iter::once(enforced.clone()));
307            }
308        }
309        *self.theater.lock().unwrap() = image.data;
310        self.refresh_index_charge();
311        Ok(())
312    }
313
314    fn validate_checkpoint_theater_image(&self, image: &CheckpointTheater) -> Result<()> {
315        Self::validate_checkpoint_theater_image_in(image, &self.catalog.lock().unwrap())
316    }
317
318    /// The image checks over an explicit catalog view: the restore path
319    /// validates against the catalog as the re-derivation leaves it, without
320    /// committing the migration before the image is accepted.
321    fn validate_checkpoint_theater_image_in(
322        image: &CheckpointTheater,
323        catalog: &Catalog,
324    ) -> Result<()> {
325        Self::validate_legacy_unknown(image, catalog)?;
326        Self::validate_enforced_label_completeness(image, catalog)?;
327        Self::validate_graph_type_derivation(image)?;
328        Self::validate_derived_identity(image, catalog)?;
329        Self::validate_index_details(image, catalog)
330    }
331
332    /// Legacy-unknown markers name rows the catalog still carries and the
333    /// derived index does not shadow.
334    fn validate_legacy_unknown(image: &CheckpointTheater, catalog: &Catalog) -> Result<()> {
335        for (name, def) in &image.legacy_unknown_constraints {
336            if name != &def.name
337                || !requires_enforced_label(def)
338                || catalog.constraints.get(name) != Some(def)
339                || image.data.derived_constraints.contains_key(name)
340            {
341                return Err(Error::storage(
342                    "checkpoint legacy-unknown constraint does not match its named definition",
343                ));
344            }
345        }
346        Ok(())
347    }
348
349    /// Every enforced-label constraint has a matching derived record or a
350    /// recorded legacy marker; a complete image may not leave one dangling.
351    fn validate_enforced_label_completeness(
352        image: &CheckpointTheater,
353        catalog: &Catalog,
354    ) -> Result<()> {
355        for def in catalog
356            .constraints
357            .values()
358            .filter(|d| requires_enforced_label(d))
359        {
360            // One probe, flat arms: a matching derived record, or a recorded
361            // legacy marker for an absent record; anything else is a missing
362            // match.
363            match image.data.derived_constraints.get(&def.name) {
364                Some(constraint) if matching_enforced_label(def, constraint) => {}
365                None if image.legacy_unknown_constraints.get(&def.name) == Some(def) => {}
366                _ => {
367                    return Err(Error::storage(
368                        "checkpoint named label constraint is missing matching enforced label",
369                    ))
370                }
371            }
372        }
373        Ok(())
374    }
375
376    /// The persisted graph type derives exactly the constraints the theater
377    /// lists.
378    fn validate_graph_type_derivation(image: &CheckpointTheater) -> Result<()> {
379        for expected in
380            crate::graph_type::derive_constraints(&image.data.current_graph_type.to_body())
381                .map_err(crate::graph_type::persisted_derive_error)?
382        {
383            if image.data.derived_constraints.get(&expected.name) != Some(&expected) {
384                return Err(Error::storage(
385                    "checkpoint graph type is missing a derived constraint",
386                ));
387            }
388        }
389        Ok(())
390    }
391
392    /// Every derived record's key, kind, entity side, and enforced label are
393    /// coherent with the catalog.
394    fn validate_derived_identity(image: &CheckpointTheater, catalog: &Catalog) -> Result<()> {
395        for (name, constraint) in &image.data.derived_constraints {
396            // One typed boundary for both identity facts: the entry's key is
397            // its record's name, and `entity_type` is one of the two rendered
398            // kinds. Any other spelling is corruption — the same
399            // model classifier the WAL preflight uses.
400            let kind = match constraint.entity_kind() {
401                Ok(kind) if name == &constraint.name => kind,
402                _ => {
403                    return Err(Error::storage(
404                        "invalid checkpoint derived constraint identity",
405                    ))
406                }
407            };
408            let label_kind = constraint.constraint_type.is_enforced_label_kind();
409            let has_label = super::has_enforced_label(constraint);
410            let relationship = kind.is_relationship();
411            let wrong_entity = constraint
412                .constraint_type
413                .enforced_label_site()
414                .is_some_and(|site| site.is_relationship() != relationship);
415            if wrong_entity {
416                return Err(Error::storage(
417                    "checkpoint enforced-label entity type mismatch",
418                ));
419            }
420            if label_kind && !has_label {
421                return Err(Error::storage(
422                    "checkpoint constraint is missing its enforced label",
423                ));
424            }
425            if constraint.enforced_label.is_some() {
426                let matches = catalog.constraints.values().any(|def| {
427                    (def.name == *name || !catalog.constraints.contains_key(name))
428                        && matching_enforced_label(def, constraint)
429                });
430                if !matches || !has_label {
431                    return Err(Error::storage(
432                        "invalid checkpoint enforced-label constraint",
433                    ));
434                }
435            }
436        }
437        Ok(())
438    }
439
440    /// Every index detail/option names a live index (the same
441    /// `(image, &Catalog)` shape as its four siblings).
442    fn validate_index_details(image: &CheckpointTheater, catalog: &Catalog) -> Result<()> {
443        for name in image
444            .data
445            .index_details
446            .keys()
447            .chain(image.data.index_options.keys())
448        {
449            if !catalog.indexes.contains_key(name) {
450                return Err(Error::storage("checkpoint index detail has no named index"));
451            }
452        }
453        Ok(())
454    }
455
456    /// Recover the legacy GraphData enforced-label field when no typed theater
457    /// image exists. Base definitions must already be installed.
458    #[doc(hidden)]
459    pub fn restore_legacy_enforced_constraints(
460        &self,
461        constraints: Vec<relate_model::Constraint>,
462    ) -> Result<()> {
463        let mut image = self.checkpoint_theater();
464        for constraint in constraints {
465            // Legacy GraphData may omit the theater entirely: validate the
466            // supplied entries one by one (typed identity plus a matching
467            // catalog definition) instead of imposing the typed image's
468            // completeness guarantee.
469            self.validate_legacy_enforced_entry(&constraint)?;
470            image
471                .data
472                .derived_constraints
473                .insert(constraint.name.clone(), constraint);
474        }
475        self.install_checkpoint_theater_image(image)
476    }
477
478    /// The legacy entry gate: a typed entity kind, an enforced-label kind,
479    /// a non-empty label, and a catalog definition it matches.
480    fn validate_legacy_enforced_entry(&self, constraint: &relate_model::Constraint) -> Result<()> {
481        constraint.entity_kind().map_err(Error::storage)?;
482        let catalog = self.catalog.lock().unwrap();
483        let matches = catalog
484            .constraints
485            .values()
486            .any(|def| matching_enforced_label(def, constraint));
487        if !super::has_enforced_label(constraint) || !matches {
488            return Err(Error::storage(
489                "invalid checkpoint enforced-label constraint",
490            ));
491        }
492        Ok(())
493    }
494}
495
496#[cfg(test)]
497mod tests {
498    use super::*;
499    use crate::redo::{IndexDetailSpec, IndexKindSpec};
500
501    fn range_index_detail() -> IndexDetailSpec {
502        IndexDetailSpec {
503            kind: IndexKindSpec::Range,
504            relationship: false,
505            labels: vec!["N".into()],
506            properties: vec!["p".into()],
507            with_properties: Vec::new(),
508        }
509    }
510
511    fn admitted_show() -> ShowSchema {
512        ShowSchema::capture(
513            DatabasesCatalog::default().snapshot(),
514            &TheaterData::default(),
515        )
516    }
517
518    #[test]
519    fn apply_overlay_propagates_corrupt_index_options() {
520        let mut show = admitted_show();
521        let ops = vec![RedoOp::CatalogIndexDetail {
522            name: "idx".into(),
523            detail: range_index_detail(),
524            options: serde_json::json!("corrupted"),
525        }];
526        // A decode failure is an error, never a silently dropped index entry
527        // (matching `Graph::apply_redo`).
528        assert!(apply_show_overlay(&mut show, &ops).is_err());
529        assert!(show.data.index_details.is_empty());
530        assert!(show.data.index_options.is_empty());
531    }
532
533    #[test]
534    fn apply_overlay_installs_valid_index_options() {
535        let mut show = admitted_show();
536        let ops = vec![RedoOp::CatalogIndexDetail {
537            name: "idx".into(),
538            detail: range_index_detail(),
539            options: serde_json::json!({}),
540        }];
541        apply_show_overlay(&mut show, &ops).unwrap();
542        assert!(show.data.index_details.contains_key("idx"));
543        assert!(show.data.index_options.contains_key("idx"));
544    }
545
546    /// ADR-0116 §1/§8/§10: the default store-level catalog carries exactly
547    /// the three fixed namespaces.
548    #[test]
549    fn default_catalog_has_exactly_the_fixed_namespaces() {
550        let catalog = DatabasesCatalog::default();
551        let snapshot = catalog.snapshot();
552        let names: Vec<Namespace> = snapshot.keys().copied().collect();
553        assert_eq!(names, Namespace::ALL);
554    }
555
556    /// ADR-0116 §8: `PutDatabase` redo for a non-fixed name (an older
557    /// store's `CREATE DATABASE` theater) is dropped at the replay
558    /// boundary; fixed names match case-insensitively and store under the
559    /// typed key, and a `DropDatabase` redo is a no-op because the fixed
560    /// namespaces can never be dropped. The speculative overlay and the
561    /// committed store-level catalog apply the same rule.
562    #[test]
563    fn database_ops_keep_only_the_fixed_namespaces() {
564        let ops = [
565            RedoOp::PutDatabase {
566                name: "analytics".into(),
567                language: 5,
568                composite: false,
569            },
570            RedoOp::PutDatabase {
571                name: "Neo4j".into(),
572                language: 5,
573                composite: false,
574            },
575            RedoOp::DropDatabase {
576                name: "system".into(),
577            },
578        ];
579        let mut show = admitted_show();
580        apply_show_overlay(&mut show, &ops).unwrap();
581        let names: Vec<Namespace> = show.databases.keys().copied().collect();
582        assert_eq!(names, Namespace::ALL);
583        assert_eq!(
584            show.databases[&Namespace::Neo4j],
585            DatabaseEntry {
586                default_language: 5,
587                composite: false,
588            }
589        );
590
591        let catalog = DatabasesCatalog::default();
592        for op in &ops {
593            match op {
594                RedoOp::PutDatabase {
595                    name,
596                    language,
597                    composite,
598                } => catalog.put_database(name, *language, *composite),
599                RedoOp::DropDatabase { .. } => {}
600                _ => unreachable!(),
601            }
602        }
603        assert_eq!(catalog.snapshot(), show.databases);
604    }
605
606    /// ADR-0116 §8: the boundary conversion for a checkpoint image drops
607    /// non-fixed entries and fills any missing fixed namespace with its
608    /// default.
609    #[test]
610    fn sanitize_databases_drops_non_fixed_and_fills_defaults() {
611        let mut map = BTreeMap::new();
612        map.insert(
613            "analytics".to_string(),
614            DatabaseEntry {
615                default_language: 5,
616                composite: false,
617            },
618        );
619        map.insert(
620            "NEO4J".to_string(),
621            DatabaseEntry {
622                default_language: 5,
623                composite: true,
624            },
625        );
626        let fixed = DatabasesCatalog::sanitize(&map);
627        let names: Vec<Namespace> = fixed.keys().copied().collect();
628        assert_eq!(names, Namespace::ALL);
629        assert_eq!(
630            fixed[&Namespace::Neo4j],
631            DatabaseEntry {
632                default_language: 5,
633                composite: true,
634            }
635        );
636        assert_eq!(
637            fixed[&Namespace::System],
638            DatabasesCatalog::DEFAULT_DATABASE_ENTRY
639        );
640        assert_eq!(
641            fixed[&Namespace::SystemOntologies],
642            DatabasesCatalog::DEFAULT_DATABASE_ENTRY
643        );
644    }
645
646    /// The derived-constraint index is a pure function of the persisted
647    /// graph type, but its generated names are internal bookkeeping that has
648    /// changed across releases (and the property-type `NOT NULL` split
649    /// reshaped one rule). A checkpoint image written before such a change
650    /// must re-derive on restore instead of failing its identity checks.
651    #[test]
652    fn restore_rederives_a_pre_generated_name_theater() {
653        use relate_model::{ConstraintType, EntityKind};
654
655        use crate::exec::test_support::exec_autocommit;
656
657        let source = Graph::default();
658        exec_autocommit(
659            &source,
660            "ALTER CURRENT GRAPH TYPE SET { (:Person => {name :: STRING NOT NULL}) }",
661        )
662        .unwrap();
663        let mut image = source.checkpoint_theater();
664        // Age the image: the readable name the pre-split derivation
665        // generated, with `NOT NULL` still spelled into the property type
666        // (the separate existence constraint did not exist yet).
667        let legacy = relate_model::Constraint {
668            name: "constraint_propertyType_Person_name".into(),
669            label: "Person".into(),
670            properties: vec!["name".into()],
671            constraint_type: ConstraintType::PropertyType,
672            property_type: Some("STRING NOT NULL".into()),
673            entity_type: "NODE".into(),
674            enforced_label: None,
675        };
676        image.data.derived_constraints =
677            std::iter::once((legacy.name.clone(), legacy.clone())).collect::<BTreeMap<_, _>>();
678
679        let graph = Graph::default();
680        graph
681            .install_named_constraint(ConstraintDef::from_model(&legacy, EntityKind::Node))
682            .unwrap();
683        graph
684            .restore_checkpoint_theater(image)
685            .expect("a pre-generated-name image re-derives and restores");
686
687        let theater = graph.theater.lock().unwrap();
688        let expected =
689            crate::graph_type::derived_constraints_map(&theater.current_graph_type.to_body())
690                .unwrap();
691        assert_eq!(theater.derived_constraints, expected);
692        drop(theater);
693        let mut rows = graph.named_constraints();
694        rows.sort_by(|a, b| a.name.cmp(&b.name));
695        assert_eq!(rows.len(), 2, "{rows:?}");
696        assert!(
697            rows.iter().all(|def| def.name.starts_with("constraint_")),
698            "{rows:?}"
699        );
700        let property_type = rows
701            .iter()
702            .find(|def| def.kind == "propertyType")
703            .expect("the property-type row survives the re-derivation");
704        assert_eq!(property_type.property_type.as_deref(), Some("STRING"));
705    }
706
707    /// A WAL record written by an older binary installs its readable-named
708    /// rows and then replaces the graph type. Replaying it must not leave
709    /// the catalog behind the re-derived index: the stale `"<type> NOT
710    /// NULL"` row would survive every purge and turn the next non-`SET`
711    /// ALTER into a conflict.
712    #[test]
713    fn replaying_a_pre_generated_name_record_keeps_the_catalog_current() {
714        use relate_model::{ConstraintType, EntityKind};
715
716        use crate::exec::test_support::exec_autocommit;
717
718        let graph = Graph::default();
719        exec_autocommit(
720            &graph,
721            "ALTER CURRENT GRAPH TYPE SET { (:Person => {name :: STRING NOT NULL}) }",
722        )
723        .unwrap();
724        let body = graph.checkpoint_theater().data.current_graph_type.clone();
725        let committed: Vec<String> = graph
726            .named_constraints()
727            .into_iter()
728            .map(|def| def.name)
729            .collect();
730        assert_eq!(committed.len(), 2, "{committed:?}");
731
732        // The pre-PR record: purge the committed set, install the
733        // readable-name rows, then carry the new body.
734        let legacy = relate_model::Constraint {
735            name: "constraint_propertyType_Person_name".into(),
736            label: "Person".into(),
737            properties: vec!["name".into()],
738            constraint_type: ConstraintType::PropertyType,
739            property_type: Some("STRING NOT NULL".into()),
740            entity_type: "NODE".into(),
741            enforced_label: None,
742        };
743        let mut ops: Vec<RedoOp> = committed
744            .into_iter()
745            .map(|name| RedoOp::DropConstraint { name })
746            .collect();
747        ops.push(RedoOp::create_constraint(ConstraintDef::from_model(
748            &legacy,
749            EntityKind::Node,
750        )));
751        ops.push(RedoOp::CatalogDerivedConstraint { constraint: legacy });
752        ops.push(RedoOp::SetCurrentGraphType { body });
753        graph.apply_redo(ops, graph.commit_ts() + 1).unwrap();
754
755        let mut rows = graph.named_constraints();
756        rows.sort_by(|a, b| a.name.cmp(&b.name));
757        assert_eq!(rows.len(), 2, "{rows:?}");
758        assert!(
759            rows.iter().all(|def| def.name.starts_with("constraint_")),
760            "{rows:?}"
761        );
762        assert!(
763            rows.iter()
764                .any(|def| def.property_type.as_deref() == Some("STRING")),
765            "{rows:?}"
766        );
767
768        // The first non-SET ALTER after the upgrade re-syncs the derived
769        // set, and a repeated one stays a no-op.
770        let alter = "ALTER CURRENT GRAPH TYPE ALTER { (:Person => {name :: STRING NOT NULL, nickname :: STRING}) }";
771        exec_autocommit(&graph, alter).expect("the upgraded store's ALTER re-syncs cleanly");
772        let after = graph.named_constraints().len();
773        exec_autocommit(&graph, alter).expect("a repeated ALTER stays idempotent");
774        assert_eq!(graph.named_constraints().len(), after);
775    }
776}