use std::collections::{BTreeMap, BTreeSet};
use relate_catalog::{derived_install_disposition, Catalog, ConstraintDef, RuleDisposition};
use relate_core::{Error, Result};
use crate::redo;
use super::theater::TheaterData;
use super::Graph;
pub(super) fn rederive_derived_constraints(
data: &mut TheaterData,
catalog: &mut Catalog,
) -> Result<()> {
if data.current_graph_type == Default::default() {
return Ok(());
}
let derived = crate::graph_type::persisted_derived_map(&data.current_graph_type)?;
if data.derived_constraints.is_empty() || data.derived_constraints == derived {
return Ok(());
}
let migration = plan_derived_migration(
&data.derived_constraints,
&derived,
catalog,
UnmatchedRecords::Keep,
&data.current_graph_type,
)?;
migration.apply_to_catalog(catalog)?;
migration.apply_to_theater(data);
Ok(())
}
impl Graph {
pub(super) fn apply_current_graph_type(
&self,
body: &crate::graph_type::GraphTypeSpec,
) -> Result<()> {
let derived = crate::graph_type::persisted_derived_map(body)?;
let previous = self.theater.lock().unwrap().derived_constraints.clone();
let migration = {
let mut catalog = self.catalog.lock().unwrap();
let migration = plan_derived_migration(
&previous,
&derived,
&catalog,
UnmatchedRecords::Drop,
body,
)?;
migration.apply_to_catalog(&mut catalog)?;
self.legacy_unenforced.lock().unwrap().retain(|name, _| {
!catalog.constraints.get(name).is_some_and(|def| {
derived
.get(name)
.is_some_and(|constraint| super::matching_enforced_label(def, constraint))
})
});
migration
};
migration.apply_to_theater(&mut self.theater.lock().unwrap());
if migration.changed() {
self.refresh_index_charge();
self.recompute_used();
}
self.rebuild_constraint_keys();
Ok(())
}
}
struct PlannedInstall {
def: ConstraintDef,
backing: Option<(relate_catalog::IndexDef, redo::IndexDetailSpec)>,
}
struct DerivedMigration {
renames: Vec<(String, String)>,
drops: Vec<ConstraintDef>,
installs: Vec<PlannedInstall>,
spec: crate::graph_type::GraphTypeSpec,
derived: BTreeMap<String, relate_model::Constraint>,
}
enum UnmatchedRecords {
Keep,
Drop,
}
fn plan_derived_migration(
previous: &BTreeMap<String, relate_model::Constraint>,
derived: &BTreeMap<String, relate_model::Constraint>,
catalog: &Catalog,
unmatched: UnmatchedRecords,
spec: &crate::graph_type::GraphTypeSpec,
) -> Result<DerivedMigration> {
let mut migration = DerivedMigration {
renames: Vec::new(),
drops: Vec::new(),
installs: Vec::new(),
spec: spec.clone(),
derived: derived.clone(),
};
for (old_name, record) in previous {
if derived.get(old_name) == Some(record) {
continue;
}
if let Some((new_name, _)) = derived.iter().find(|(_, new)| same_rule(new, record)) {
migration.renames.push((old_name.clone(), new_name.clone()));
} else if derived
.iter()
.any(|(_, new)| same_rule_before_not_null_split(new, record))
{
migration.drops.push(record_def(record)?);
} else {
match unmatched {
UnmatchedRecords::Keep => {
migration.derived.insert(old_name.clone(), record.clone());
}
UnmatchedRecords::Drop => {
migration.drops.push(record_def(record)?);
}
}
}
}
let retired: BTreeSet<&str> = migration
.drops
.iter()
.map(|def| def.name.as_str())
.collect();
let held = HeldRows::of(catalog, &retired);
for record in derived.values() {
if let Some(install) = planned_install(&held, &migration.installs, record)? {
migration.installs.push(install);
}
}
Ok(migration)
}
fn record_def(record: &relate_model::Constraint) -> Result<ConstraintDef> {
let entity = record.entity_kind().map_err(Error::storage)?;
Ok(ConstraintDef::from_model(record, entity))
}
fn planned_install(
held: &HeldRows<'_>,
planned: &[PlannedInstall],
record: &relate_model::Constraint,
) -> Result<Option<PlannedInstall>> {
let def = record_def(record)?;
if held.holds_pair_of(record, &def) {
return Ok(None);
}
let live = held
.constraints
.values()
.copied()
.filter(|row| row.name != def.name)
.chain(planned.iter().map(|install| &install.def));
match derived_install_disposition(live, &def) {
RuleDisposition::Equivalent(_) => Ok(None),
RuleDisposition::Conflicts => Err(Error::storage(
"graph type derived constraint conflicts with an existing constraint",
)),
RuleDisposition::New => {
let backing = redo::constraint_backing_pair(&def)?;
Ok(Some(PlannedInstall { def, backing }))
}
}
}
struct HeldRows<'a> {
constraints: BTreeMap<&'a str, &'a ConstraintDef>,
indexes: BTreeSet<&'a str>,
}
impl<'a> HeldRows<'a> {
fn of(catalog: &'a Catalog, retired: &BTreeSet<&str>) -> Self {
Self {
constraints: catalog
.constraints
.iter()
.filter(|(name, _)| !retired.contains(name.as_str()))
.map(|(name, row)| (name.as_str(), row))
.collect(),
indexes: catalog
.indexes
.keys()
.filter(|name| !retired.contains(name.as_str()))
.map(String::as_str)
.collect(),
}
}
fn holds_pair_of(&self, record: &relate_model::Constraint, def: &ConstraintDef) -> bool {
let row_held = self.constraints.get(def.name.as_str()).is_some_and(|held| {
let mut resolved = (*held).clone();
super::resolve_enforced_label(&mut resolved, record.enforced_label.as_deref());
resolved == *def
});
let backing_held = !def.is_index_backed() || self.indexes.contains(def.name.as_str());
row_held && backing_held
}
}
impl DerivedMigration {
fn changed(&self) -> bool {
!(self.renames.is_empty() && self.drops.is_empty() && self.installs.is_empty())
}
fn apply_to_theater(&self, data: &mut TheaterData) {
data.current_graph_type = self.spec.clone();
for (old, new) in &self.renames {
move_key(&mut data.index_details, old, new, |_, _| {});
move_key(&mut data.index_options, old, new, |_, _| {});
}
for def in &self.drops {
if def.is_index_backed() {
data.index_details.remove(&def.name);
data.index_options.remove(&def.name);
}
}
for install in &self.installs {
if let Some((_, detail)) = &install.backing {
let name = install.def.name.clone();
data.index_details.insert(name.clone(), detail.clone());
data.index_options.insert(name, BTreeMap::new());
}
}
data.derived_constraints = self.derived.clone();
}
fn apply_to_catalog(&self, catalog: &mut Catalog) -> Result<()> {
for (old, new) in &self.renames {
move_key(&mut catalog.constraints, old, new, |def, name| {
def.name = name.to_string();
});
move_key(&mut catalog.indexes, old, new, |index, name| {
index.name = name.to_string();
});
}
for def in &self.drops {
drop_derived_row(catalog, def)?;
}
for install in &self.installs {
catalog.insert_constraint(install.def.clone())?;
if let Some((row, _)) = &install.backing {
catalog.insert_index(row.clone())?;
}
}
Ok(())
}
}
fn move_key<V>(
map: &mut BTreeMap<String, V>,
old: &str,
new: &str,
rename: impl FnOnce(&mut V, &str),
) {
if map.contains_key(new) {
map.remove(old);
return;
}
if let Some(mut value) = map.remove(old) {
rename(&mut value, new);
map.insert(new.to_string(), value);
}
}
fn same_rule(left: &relate_model::Constraint, right: &relate_model::Constraint) -> bool {
left.entity_type == right.entity_type
&& left.label == right.label
&& left.properties == right.properties
&& left.constraint_type == right.constraint_type
&& left.property_type == right.property_type
&& left.enforced_label == right.enforced_label
}
const NOT_NULL_SUFFIX: &str = " NOT NULL";
fn same_rule_before_not_null_split(
derived: &relate_model::Constraint,
legacy: &relate_model::Constraint,
) -> bool {
let Some(bare_type) = legacy
.property_type
.as_deref()
.and_then(|property_type| property_type.strip_suffix(NOT_NULL_SUFFIX))
else {
return false;
};
let mut normalized = legacy.clone();
normalized.property_type = Some(bare_type.to_string());
same_rule(derived, &normalized)
}
fn drop_derived_row(catalog: &mut Catalog, def: &ConstraintDef) -> Result<()> {
if let Some(existing) = catalog.constraints.get(&def.name) {
if existing != def {
return Err(Error::storage(
"checkpoint derived constraint does not match its catalog row",
));
}
catalog.constraints.remove(&def.name);
}
if def.is_index_backed() {
catalog.indexes.remove(&def.name);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use relate_model::{Constraint, ConstraintType};
fn property_type_record(name: &str, property_type: &str) -> Constraint {
Constraint {
name: name.to_string(),
label: "D".to_string(),
properties: vec!["p".to_string()],
constraint_type: ConstraintType::PropertyType,
property_type: Some(property_type.to_string()),
entity_type: "NODE".to_string(),
enforced_label: None,
}
}
fn key_record(name: &str) -> Constraint {
Constraint {
name: name.to_string(),
label: "Person".to_string(),
properties: vec!["title".to_string()],
constraint_type: ConstraintType::Key,
property_type: None,
entity_type: "NODE".to_string(),
enforced_label: None,
}
}
fn committed_schema_body() -> relate_parser::GraphTypeBody {
relate_parser::parse_graph_type_body(
"(:Person => {title :: STRING IS KEY}), (:Person=>)-[:KNOWS=>]->(:Person=>)",
)
.expect("parses")
}
#[test]
fn a_bare_graph_type_record_installs_its_derived_catalog_rows() {
let g = Graph::default();
let spec = crate::graph_type::GraphTypeSpec::from_body(&committed_schema_body())
.expect("shape-validated body");
g.apply_redo(
vec![crate::redo::RedoOp::SetCurrentGraphType { body: spec }],
1,
)
.expect("the bare record applies");
let mut rows: Vec<(String, String, Vec<String>)> = g
.named_constraints()
.into_iter()
.map(|def| (def.kind, def.label, def.properties))
.collect();
rows.sort();
assert_eq!(
rows,
vec![
(
"key".to_string(),
"Person".to_string(),
vec!["title".to_string()]
),
(
"propertyType".to_string(),
"Person".to_string(),
vec!["title".to_string()]
),
("sourceLabel".to_string(), "KNOWS".to_string(), Vec::new()),
("targetLabel".to_string(), "KNOWS".to_string(), Vec::new()),
],
"the derived set is the catalog's constraint rows"
);
let key = g
.named_constraints()
.into_iter()
.find(|def| def.kind == "key")
.expect("the derived key constraint is a catalog row");
assert!(
g.named_indexes().iter().any(|index| index.name == key.name),
"the index-backed kind owns its backing index row"
);
g.checkpoint_theater_for_write()
.expect("the theater image validates for the checkpoint write");
}
#[test]
fn a_nested_not_null_legacy_type_matches_its_split_derivation() {
let derived = property_type_record("constraint_1", "LIST<STRING NOT NULL>");
let legacy = property_type_record("legacy", "LIST<STRING NOT NULL> NOT NULL");
assert!(same_rule_before_not_null_split(&derived, &legacy));
}
#[test]
fn a_scalar_not_null_legacy_type_matches_its_split_derivation() {
let derived = property_type_record("constraint_1", "BOOLEAN");
let legacy = property_type_record("legacy", "BOOLEAN NOT NULL");
assert!(same_rule_before_not_null_split(&derived, &legacy));
}
#[test]
fn an_unrelated_legacy_type_is_not_a_split_match() {
let derived = property_type_record("constraint_1", "BOOLEAN");
let legacy = property_type_record("legacy", "INTEGER NOT NULL");
assert!(!same_rule_before_not_null_split(&derived, &legacy));
}
#[test]
fn a_nested_not_null_legacy_record_is_dropped_not_kept() {
let previous = BTreeMap::from([(
"legacy".to_string(),
property_type_record("legacy", "LIST<STRING NOT NULL> NOT NULL"),
)]);
let derived = BTreeMap::from([(
"constraint_1".to_string(),
property_type_record("constraint_1", "LIST<STRING NOT NULL>"),
)]);
let migration = plan_derived_migration(
&previous,
&derived,
&Catalog::default(),
UnmatchedRecords::Keep,
&crate::graph_type::GraphTypeSpec::default(),
)
.expect("the split match plans");
assert_eq!(migration.drops.len(), 1, "the stale row is dropped");
assert_eq!(migration.drops[0].name, "legacy");
assert!(!migration.derived.contains_key("legacy"));
}
#[test]
fn a_fresh_record_installs_over_the_row_it_retires() {
let stale = property_type_record("constraint_1", "LIST<STRING NOT NULL> NOT NULL");
let fresh = property_type_record("constraint_1", "LIST<STRING NOT NULL>");
let previous = BTreeMap::from([("constraint_1".to_string(), stale)]);
let derived = BTreeMap::from([("constraint_1".to_string(), fresh)]);
let mut catalog = Catalog::default();
catalog
.insert_constraint(record_def(&previous["constraint_1"]).expect("typed record"))
.expect("the stale row seeds the catalog");
let migration = plan_derived_migration(
&previous,
&derived,
&catalog,
UnmatchedRecords::Drop,
&crate::graph_type::GraphTypeSpec::default(),
)
.expect("the same-name plan builds");
assert_eq!(migration.drops.len(), 1, "the stale row is retired");
assert_eq!(
migration.installs.len(),
1,
"the fresh same-named record installs over the retired row"
);
assert_eq!(migration.installs[0].def.name, "constraint_1");
}
#[test]
fn a_kept_rider_never_installs() {
let rider = property_type_record("user_rule", "BOOLEAN");
let fresh = property_type_record("constraint_1", "BOOLEAN NOT NULL");
let previous = BTreeMap::from([("user_rule".to_string(), rider)]);
let derived = BTreeMap::from([("constraint_1".to_string(), fresh)]);
let migration = plan_derived_migration(
&previous,
&derived,
&Catalog::default(),
UnmatchedRecords::Keep,
&crate::graph_type::GraphTypeSpec::default(),
)
.expect("the rider plan builds");
assert!(
migration.derived.contains_key("user_rule"),
"the rider rides over verbatim"
);
assert!(
!migration
.installs
.iter()
.any(|install| install.def.name == "user_rule"),
"the rider's missing row is not healed by an install"
);
}
#[test]
fn a_held_row_with_a_missing_backing_index_heals() {
let key = key_record("constraint_k");
let derived = BTreeMap::from([("constraint_k".to_string(), key.clone())]);
let mut catalog = Catalog::default();
catalog
.insert_constraint(record_def(&key).expect("typed record"))
.expect("the constraint row seeds the catalog");
let migration = plan_derived_migration(
&BTreeMap::new(),
&derived,
&catalog,
UnmatchedRecords::Drop,
&crate::graph_type::GraphTypeSpec::default(),
)
.expect("the heal plan builds");
assert_eq!(
migration.installs.len(),
1,
"the missing backing half re-plans its install"
);
migration
.apply_to_catalog(&mut catalog)
.expect("the heal applies");
assert!(
catalog.indexes.contains_key("constraint_k"),
"the backing index row is healed beside its held constraint row"
);
let mut theater = TheaterData::default();
migration.apply_to_theater(&mut theater);
assert!(
theater.index_details.contains_key("constraint_k"),
"the healed row's seek-postings detail is installed"
);
}
#[test]
fn a_fieldless_legacy_row_under_the_name_is_the_records_own() {
let record = Constraint {
name: "constraint_s".to_string(),
label: "KNOWS".to_string(),
properties: Vec::new(),
constraint_type: ConstraintType::SourceLabel,
property_type: None,
entity_type: "RELATIONSHIP".to_string(),
enforced_label: Some("Person".to_string()),
};
let mut legacy_row = record_def(&record).expect("typed record");
legacy_row.enforced_label = None;
let mut catalog = Catalog::default();
catalog
.insert_constraint(legacy_row)
.expect("the legacy row seeds the catalog");
let derived = BTreeMap::from([("constraint_s".to_string(), record)]);
let migration = plan_derived_migration(
&BTreeMap::new(),
&derived,
&catalog,
UnmatchedRecords::Drop,
&crate::graph_type::GraphTypeSpec::default(),
)
.expect("the legacy-twin plan builds");
assert!(
migration.installs.is_empty(),
"the resolved twin is the record's own row: no install, no duplicate-gate error"
);
}
#[test]
fn a_derived_set_conflicting_with_itself_refuses() {
let key = key_record("constraint_k");
let mut unique = key_record("constraint_u");
unique.constraint_type = ConstraintType::Unique;
let derived = BTreeMap::from([
("constraint_k".to_string(), key),
("constraint_u".to_string(), unique),
]);
let err = plan_derived_migration(
&BTreeMap::new(),
&derived,
&Catalog::default(),
UnmatchedRecords::Drop,
&crate::graph_type::GraphTypeSpec::default(),
)
.map(|_| ())
.expect_err("the self-conflicting set refuses at the plan");
assert!(
err.to_string()
.contains("graph type derived constraint conflicts with an existing constraint"),
"{err}"
);
}
}