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