pub(crate) mod admission;
mod ddl;
mod estimate;
mod seams;
mod simulation;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::str::FromStr;
use relate_catalog::ConstraintDef;
use relate_core::{NodeId, RelId, Value};
use relate_model::{Constraint, ConstraintType};
use crate::group_key::GroupKey;
use crate::store::{Interner, LiveNode, LiveRel, PayloadKeyIds};
use super::Graph;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum EntityId {
Node(NodeId),
Rel(RelId),
}
pub(crate) type KeyTuple = Box<[GroupKey]>;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct ConstraintKeyScope {
pub(super) node_labels: HashSet<u32>,
pub(super) rel_types: HashSet<u32>,
pub(super) node_keys: HashSet<u32>,
pub(super) rel_keys: HashSet<u32>,
}
impl ConstraintKeyScope {
pub(super) fn from_specs<'a>(specs: impl IntoIterator<Item = &'a KeySpec>) -> Self {
let mut scope = Self::default();
for spec in specs {
scope.add_spec(spec);
}
scope
}
pub(super) fn add_spec(&mut self, spec: &KeySpec) {
match spec.side {
SpecSide::Rel { type_id } => {
self.rel_types.insert(type_id);
self.rel_keys.extend(spec.property_ids.iter().copied());
}
SpecSide::Node { label_id } => {
self.node_labels.insert(label_id);
self.node_keys.extend(spec.property_ids.iter().copied());
}
}
}
pub(super) fn touches_node(&self, labels: &[u32], keys: impl IntoIterator<Item = u32>) -> bool {
self.touches_node_labels(labels) || keys.into_iter().any(|id| self.node_keys.contains(&id))
}
pub(super) fn touches_node_labels(&self, labels: &[u32]) -> bool {
labels.iter().any(|id| self.node_labels.contains(id))
}
pub(super) fn touches_rel(&self, type_id: u32, key_ids: &PayloadKeyIds<'_>) -> bool {
self.rel_types.contains(&type_id) || key_ids.any(|kid| self.rel_keys.contains(&kid))
}
pub(super) fn touches_node_key(&self, key_id: u32) -> bool {
self.node_keys.contains(&key_id)
}
pub(super) fn touches_rel_key(&self, key_id: u32) -> bool {
self.rel_keys.contains(&key_id)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SpecSide {
Node { label_id: u32 },
Rel { type_id: u32 },
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct KeySpec {
pub(crate) name: String,
pub(crate) side: SpecSide,
pub(crate) property_ids: Box<[u32]>,
}
impl KeySpec {
pub(super) fn new(
interner: &Interner,
name: String,
relationship: bool,
label: String,
properties: Vec<String>,
) -> Self {
let label_id = interner.intern(&label);
let side = if relationship {
SpecSide::Rel { type_id: label_id }
} else {
SpecSide::Node { label_id }
};
let property_ids: Box<[u32]> = properties
.iter()
.map(|property| interner.intern(property))
.collect();
Self {
name,
side,
property_ids,
}
}
pub(crate) fn is_relationship(&self) -> bool {
matches!(self.side, SpecSide::Rel { .. })
}
pub(crate) fn label_id(&self) -> u32 {
match self.side {
SpecSide::Node { label_id } => label_id,
SpecSide::Rel { type_id } => type_id,
}
}
fn live_node_tuple(&self, node: &LiveNode) -> Option<KeyTuple> {
let SpecSide::Node { label_id } = self.side else {
return None;
};
if !node.labels.contains(&label_id) {
return None;
}
Self::tuple_of(self.property_ids.iter().map(|&kid| node.props.get(kid)))
}
fn live_rel_tuple(&self, interner: &Interner, rel: &LiveRel) -> Option<KeyTuple> {
let SpecSide::Rel { type_id } = self.side else {
return None;
};
if rel.type_id != type_id {
return None;
}
let mut values: Vec<Option<Value>> = vec![None; self.property_ids.len()];
rel.payload.for_each_key_value(interner, |kid, value| {
if let Some(slot) = self.property_ids.iter().position(|&wanted| wanted == kid) {
values[slot] = Some(value.clone());
}
});
Self::tuple_of(values.iter().map(Option::as_ref))
}
fn tuple_of<'a>(values: impl ExactSizeIterator<Item = Option<&'a Value>>) -> Option<KeyTuple> {
let mut keys = Vec::with_capacity(values.len());
for value in values {
let value = value?;
if value.is_null() {
return None;
}
keys.push(GroupKey::for_property_index(value)?);
}
Some(keys.into_boxed_slice())
}
}
#[derive(Debug)]
struct KeyedConstraint {
spec: KeySpec,
entries: HashMap<KeyTuple, TupleEntry>,
}
#[derive(Debug)]
struct TupleEntry {
holders: Vec<EntityId>,
charged: u64,
}
impl KeyedConstraint {
fn backfilled(graph: &Graph, spec: KeySpec) -> Self {
let entries = graph.backfill_constraint(&spec);
Self { spec, entries }
}
fn charge_total(&self) -> u64 {
self.entries.values().map(|entry| entry.charged).sum()
}
}
impl TupleEntry {
fn refund_for(&self, entity: EntityId) -> Option<u64> {
if !self.holders.contains(&entity) {
return None;
}
if self.holders.iter().all(|holder| *holder == entity) {
Some(self.charged)
} else {
Some(HOLDER_BYTES)
}
}
}
#[derive(Debug, Default)]
pub(crate) struct ConstraintKeyIndex {
constraints: BTreeMap<String, KeyedConstraint>,
scope: ConstraintKeyScope,
}
impl ConstraintKeyIndex {
fn is_empty(&self) -> bool {
self.constraints.is_empty()
}
pub(super) fn scope(&self) -> &ConstraintKeyScope {
&self.scope
}
fn refresh_scope(&mut self) {
self.scope = ConstraintKeyScope::from_specs(self.constraints.values().map(|kc| &kc.spec));
}
#[cfg(test)]
pub(super) fn spec(&self, name: &str) -> Option<&KeySpec> {
self.constraints.get(name).map(|kc| &kc.spec)
}
pub(super) fn specs(&self) -> impl Iterator<Item = &KeySpec> {
self.constraints.values().map(|kc| &kc.spec)
}
fn charge_total(&self) -> u64 {
self.constraints
.values()
.map(KeyedConstraint::charge_total)
.sum()
}
pub(super) fn charge_of(&self, name: &str) -> u64 {
self.constraints
.get(name)
.expect("a maintained constraint's map entry exists")
.charge_total()
}
pub(super) fn refund_for(&self, name: &str, tuple: &KeyTuple, entity: EntityId) -> u64 {
let Some(kc) = self.constraints.get(name) else {
return 0;
};
kc.entries
.get(tuple)
.and_then(|entry| entry.refund_for(entity))
.unwrap_or(0)
}
fn install(&mut self, kc: KeyedConstraint) -> u64 {
let name = kc.spec.name.clone();
let refunded = self.take(&name);
self.constraints.insert(name, kc);
self.refresh_scope();
refunded
}
fn replace_all(&mut self, kcs: impl IntoIterator<Item = KeyedConstraint>) {
self.constraints = kcs
.into_iter()
.map(|kc| (kc.spec.name.clone(), kc))
.collect();
self.refresh_scope();
}
fn take(&mut self, name: &str) -> u64 {
self.constraints
.remove(name)
.map(|kc| kc.charge_total())
.unwrap_or(0)
}
pub(super) fn holders(&self, name: &str, tuple: &KeyTuple) -> Vec<EntityId> {
self.constraints
.get(name)
.expect("a maintained constraint's map entry exists")
.entries
.get(tuple)
.map(|entry| entry.holders.clone())
.unwrap_or_default()
}
fn introduce_entry(kc: &mut KeyedConstraint, tuple: KeyTuple, entity: EntityId) -> i64 {
match kc.entries.get_mut(&tuple) {
Some(entry) => {
if entry.holders.contains(&entity) {
return 0;
}
entry.holders.push(entity);
entry.charged = entry.charged.saturating_add(HOLDER_BYTES);
HOLDER_BYTES as i64
}
None => {
let charged = entry_charge(&tuple, 1);
kc.entries.insert(
tuple,
TupleEntry {
holders: vec![entity],
charged,
},
);
charged as i64
}
}
}
fn transition(
kc: &mut KeyedConstraint,
entity: EntityId,
from: Option<KeyTuple>,
to: Option<KeyTuple>,
) -> i64 {
if from == to {
return 0;
}
let freed = from
.as_ref()
.map_or(0, |tuple| Self::free_entry(kc, tuple, entity));
let introduced = to.map_or(0, |tuple| Self::introduce_entry(kc, tuple, entity));
freed + introduced
}
fn free_entry(kc: &mut KeyedConstraint, tuple: &KeyTuple, entity: EntityId) -> i64 {
let Some(entry) = kc.entries.get_mut(tuple) else {
return 0;
};
let Some(refund) = entry.refund_for(entity) else {
return 0;
};
entry.holders.retain(|holder| *holder != entity);
if entry.holders.is_empty() {
kc.entries.remove(tuple);
} else {
entry.charged = entry.charged.saturating_sub(HOLDER_BYTES);
}
-(refund as i64)
}
fn remove_constraint(&mut self, name: &str) -> u64 {
let refunded = self.take(name);
self.refresh_scope();
refunded
}
}
pub(crate) const CONSTRAINT_KEY_ENTRY_BYTES: u64 = 48 + 64;
const HOLDER_BYTES: u64 = std::mem::size_of::<EntityId>() as u64;
const COMPONENT_ESTIMATE_BYTES: u64 = 32;
fn entry_charge(tuple: &KeyTuple, holders: usize) -> u64 {
CONSTRAINT_KEY_ENTRY_BYTES
.saturating_add(tuple.iter().map(GroupKey::logical_bytes).sum())
.saturating_add((holders as u64).saturating_mul(HOLDER_BYTES))
}
pub(super) fn spec_from_def(interner: &Interner, def: &ConstraintDef) -> Option<KeySpec> {
let kind = ConstraintType::from_str(&def.kind)
.expect("Catalog::insert_constraint rejects unknown constraint kinds");
if !kind.enforces_uniqueness() {
return None;
}
Some(KeySpec::new(
interner,
def.name.clone(),
def.relationship,
def.label.clone(),
def.properties.clone(),
))
}
pub(super) fn spec_from_model(interner: &Interner, constraint: &Constraint) -> Option<KeySpec> {
if !constraint.constraint_type.enforces_uniqueness() {
return None;
}
let relationship = constraint.entity_kind().ok()?.is_relationship();
Some(KeySpec::new(
interner,
constraint.name.clone(),
relationship,
constraint.label.clone(),
constraint.properties.clone(),
))
}
impl Graph {
pub(super) fn constraint_keys_install(&self, spec: KeySpec) {
let kc = KeyedConstraint::backfilled(self, spec);
let charged = kc.charge_total();
let refunded = self.constraint_keys.lock().unwrap().install(kc);
self.charge(charged as i64 - refunded as i64);
}
pub(super) fn constraint_keys_drop(&self, name: &str) {
let refunded = self.constraint_keys.lock().unwrap().remove_constraint(name);
self.charge(-(refunded as i64));
}
fn backfill_constraint(&self, spec: &KeySpec) -> HashMap<KeyTuple, TupleEntry> {
let mut holders: HashMap<KeyTuple, Vec<EntityId>> = HashMap::new();
if spec.is_relationship() {
self.rels.for_each(|id, vers| {
let Some(live) = super::live_version(vers) else {
return;
};
if let Some(tuple) = spec.live_rel_tuple(&self.interner, live.live) {
holders.entry(tuple).or_default().push(EntityId::Rel(id));
}
});
} else {
let ids: Vec<NodeId> = self
.indexes
.label_index
.get(&spec.label_id())
.map(|set| set.iter().copied().collect())
.unwrap_or_default();
for id in ids {
let Some(vers) = self.nodes.get(&id) else {
continue;
};
let Some(live) = super::live_version(&vers) else {
continue;
};
if let Some(tuple) = spec.live_node_tuple(live.live) {
holders.entry(tuple).or_default().push(EntityId::Node(id));
}
}
}
holders
.into_iter()
.map(|(tuple, holders)| {
let charged = entry_charge(&tuple, holders.len());
(tuple, TupleEntry { holders, charged })
})
.collect()
}
fn uniqueness_specs(&self) -> Vec<KeySpec> {
let catalog_specs: Vec<KeySpec> = {
let catalog = self.catalog.lock().unwrap();
catalog
.constraints
.values()
.filter_map(|def| spec_from_def(&self.interner, def))
.collect()
};
let derived_specs: Vec<KeySpec> = {
let theater = self.theater.lock().unwrap();
theater
.derived_constraints
.values()
.filter_map(|constraint| spec_from_model(&self.interner, constraint))
.collect()
};
let mut out = Vec::with_capacity(catalog_specs.len() + derived_specs.len());
let mut seen = std::collections::HashSet::new();
for spec in catalog_specs.into_iter().chain(derived_specs) {
if seen.insert(spec.name.clone()) {
out.push(spec);
}
}
out
}
pub(super) fn rebuild_constraint_keys(&self) {
let mut index = ConstraintKeyIndex::default();
index.replace_all(
self.uniqueness_specs()
.into_iter()
.map(|spec| KeyedConstraint::backfilled(self, spec)),
);
let rebuilt = index.charge_total();
let mut current = self.constraint_keys.lock().unwrap();
let previous = current.charge_total();
*current = index;
drop(current);
self.charge(rebuilt as i64 - previous as i64);
}
pub(super) fn constraint_keys_structure_bytes(&self) -> u64 {
self.constraint_keys.lock().unwrap().charge_total()
}
}
#[cfg(test)]
mod property_tests;
#[cfg(test)]
mod tests;