use std::collections::{BTreeMap, HashMap, HashSet};
use relate_core::{Error, Result};
use super::ddl::{net_transitions, AdmissionSpec, BatchDdlState, Origin};
use super::entry_charge;
use super::estimate::{price_drop, price_install};
use super::simulation::{
constraint_effect, is_constraint_ddl, ConstraintOp, DdlOp, SlotSimulation,
};
use super::{ConstraintKeyIndex, ConstraintKeyScope, KeySpec, KeyTuple};
use crate::graph::{EntityId, Graph};
use crate::redo::RedoOp;
type TupleId = (u32, KeyTuple);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Hold {
Introduced,
Freed,
}
type TupleHolds = HashMap<TupleId, HashMap<EntityId, Hold>>;
#[derive(Debug, Default)]
struct NameTable {
names: Vec<String>,
ids: HashMap<String, u32>,
}
impl NameTable {
fn id(&mut self, name: &str) -> u32 {
if let Some(&id) = self.ids.get(name) {
return id;
}
let id = self.names.len() as u32;
self.names.push(name.to_string());
self.ids.insert(name.to_string(), id);
id
}
fn lookup(&self, name: &str) -> Option<u32> {
self.ids.get(name).copied()
}
fn name(&self, id: u32) -> &str {
self.names
.get(id as usize)
.map(String::as_str)
.expect("a tuple hold names a constraint interned in this group")
}
}
#[derive(Debug, Default)]
#[doc(hidden)]
pub struct PendingAdmission {
drops: HashSet<String>,
installs: BTreeMap<String, AdmissionSpec>,
holds: TupleHolds,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[doc(hidden)]
pub enum SlotPosition {
Followed,
Final,
}
impl SlotPosition {
#[doc(hidden)]
pub fn of(index: usize, len: usize) -> Self {
if index + 1 == len {
Self::Final
} else {
Self::Followed
}
}
}
#[doc(hidden)]
pub struct ConstraintAdmission<'g> {
graph: &'g Graph,
specs: BTreeMap<String, AdmissionSpec>,
scope: ConstraintKeyScope,
charges: BTreeMap<String, u64>,
names: NameTable,
holds: TupleHolds,
}
impl<'g> ConstraintAdmission<'g> {
#[cfg(test)]
pub fn admit(&mut self, ops: &[RedoOp]) -> Result<()> {
let pending = self.check(ops)?;
self.accept(pending);
Ok(())
}
#[cfg(test)]
pub fn check(&mut self, ops: &[RedoOp]) -> Result<PendingAdmission> {
self.check_with_earlier(ops, &mut std::iter::empty(), SlotPosition::Followed)
.map(|(pending, _growth)| pending)
}
#[doc(hidden)]
pub fn check_with_earlier<'e>(
&mut self,
ops: &[RedoOp],
mut earlier: impl Iterator<Item = &'e [RedoOp]>,
position: SlotPosition,
) -> Result<(PendingAdmission, i64)> {
if self.specs.is_empty() && !ops.iter().any(is_constraint_ddl) {
return Ok((PendingAdmission::default(), 0));
}
if position == SlotPosition::Final
&& !ops.iter().any(|op| constraint_effect(op).needs_admission())
{
return Ok((PendingAdmission::default(), 0));
}
let mut simulation = SlotSimulation::new(self.graph, &self.scope);
let mut slot_holds: TupleHolds = HashMap::new();
let mut installs = SlotInstalls::new(self.graph, &self.specs, &self.charges);
for op in ops {
match constraint_effect(op) {
ConstraintOp::Ddl(ddl) => installs.apply(ddl, &mut earlier)?,
ConstraintOp::Introduce(tuple_op) | ConstraintOp::Free(tuple_op) => {
simulation.apply_tuple(tuple_op);
}
ConstraintOp::Irrelevant => {}
}
}
let (state, mut growth) = installs.finish();
let installed_this_slot = state.installed();
let drops = state.drops().clone();
let mut frees: Vec<(TupleId, EntityId)> = Vec::new();
let mut introductions: Vec<(TupleId, EntityId)> = Vec::new();
let touched_entities = simulation.into_touched();
{
let index = self.graph.constraint_keys.lock().unwrap();
for transition in net_transitions(state.effective(), &touched_entities) {
if let Some(tuple) = &transition.from {
growth -=
index.refund_for(&transition.spec.name, tuple, transition.entity) as i64;
}
if let Some(tuple) = &transition.to {
growth += entry_charge(tuple, 1) as i64;
}
}
}
for transition in net_transitions(state.effective(), &touched_entities) {
if installed_this_slot.contains(&transition.spec.name) {
continue;
}
let entry = transition.entry;
let entity = transition.entity;
let name_id = self.names.id(&transition.spec.name);
if let Some(tuple) = transition.from {
frees.push(((name_id, tuple), entity));
}
if let Some(tuple) = transition.to {
match entry.origin {
Origin::InstalledInGroup => return Err(Error::conflict()),
Origin::Committed | Origin::InstalledThisSlot => {}
}
introductions.push(((name_id, tuple), entity));
}
}
for (id, entity) in frees {
slot_holds
.entry(id)
.or_default()
.insert(entity, Hold::Freed);
}
if !introductions.is_empty() {
let index = self.graph.constraint_keys.lock().unwrap();
for (id, entity) in introductions {
if self.introduction_conflicts(&index, &id, entity, &slot_holds) {
return Err(Error::conflict());
}
slot_holds
.entry(id)
.or_default()
.insert(entity, Hold::Introduced);
}
}
slot_holds.retain(|(id, _), _| !drops.contains(self.names.name(*id)));
let pending_installs: BTreeMap<String, AdmissionSpec> = state
.effective()
.iter()
.filter(|(name, _)| state.installed().contains(*name))
.map(|(name, admission)| (name.clone(), admission.clone()))
.collect();
Ok((
PendingAdmission {
drops,
installs: pending_installs,
holds: slot_holds,
},
growth,
))
}
#[doc(hidden)]
pub fn accept(&mut self, pending: PendingAdmission) {
for name in pending.drops {
self.specs.remove(&name);
self.forget_holds(&name);
}
for (name, mut admission) in pending.installs {
self.forget_holds(&name);
self.scope.add_spec(&admission.spec);
admission.origin = Origin::InstalledInGroup;
self.specs.insert(name, admission);
}
for (id, states) in pending.holds {
self.holds.entry(id).or_default().extend(states);
}
}
fn forget_holds(&mut self, name: &str) {
if let Some(id) = self.names.lookup(name) {
self.holds.retain(|(constraint, _), _| *constraint != id);
}
}
fn introduction_conflicts(
&self,
index: &ConstraintKeyIndex,
id: &TupleId,
entity: EntityId,
slot_holds: &TupleHolds,
) -> bool {
let mut holders = index.holders(self.names.name(id.0), &id.1);
for overlay in [&self.holds, slot_holds] {
let Some(states) = overlay.get(id) else {
continue;
};
for (holder, held) in states {
match held {
Hold::Introduced => {
if !holders.contains(holder) {
holders.push(*holder);
}
}
Hold::Freed => holders.retain(|have| have != holder),
}
}
}
holders.iter().any(|holder| *holder != entity)
}
}
struct SlotInstalls<'a, 'e> {
graph: &'a Graph,
state: BatchDdlState<'a, AdmissionSpec>,
charges: &'a BTreeMap<String, u64>,
growth: i64,
earlier_cache: Option<Vec<&'e [RedoOp]>>,
}
impl<'a, 'e> SlotInstalls<'a, 'e> {
fn new(
graph: &'a Graph,
committed: &'a BTreeMap<String, AdmissionSpec>,
charges: &'a BTreeMap<String, u64>,
) -> Self {
Self {
graph,
state: BatchDdlState::new(committed),
charges,
growth: 0,
earlier_cache: None,
}
}
fn apply(
&mut self,
ddl: DdlOp<'_>,
earlier: &mut impl Iterator<Item = &'e [RedoOp]>,
) -> Result<()> {
match ddl {
DdlOp::DropConstraint { name } => {
let step = self.state.drop_constraint(name);
self.growth += price_drop(self.charges, name, step);
}
install => {
for spec in install.installs(&self.graph.interner)? {
self.add(spec, earlier)?;
}
}
}
Ok(())
}
fn add(
&mut self,
spec: KeySpec,
earlier: &mut impl Iterator<Item = &'e [RedoOp]>,
) -> Result<()> {
if self.state.installed().contains(&spec.name) {
return Ok(());
}
let entry = AdmissionSpec {
spec: spec.clone(),
origin: Origin::InstalledThisSlot,
};
let charge = self.graph.estimate_backfill_charge(&spec);
let Some(step) = self.state.install(entry) else {
return Ok(());
};
self.growth += price_install(self.charges, &spec.name, charge, step);
let earlier = self.earlier_cache.get_or_insert_with(|| earlier.collect());
check_install(self.graph, &spec, earlier)
}
fn finish(self) -> (BatchDdlState<'a, AdmissionSpec>, i64) {
(self.state, self.growth)
}
}
fn check_install(graph: &Graph, spec: &KeySpec, earlier: &[&[RedoOp]]) -> Result<()> {
let scope = ConstraintKeyScope::from_specs(std::iter::once(spec));
let mut simulation = SlotSimulation::new(graph, &scope);
for ops in earlier {
for op in *ops {
simulation.simulate_redo(op);
}
}
let effective: BTreeMap<String, KeySpec> =
std::iter::once((spec.name.clone(), spec.clone())).collect();
for transition in net_transitions(&effective, &simulation.into_touched()) {
if transition.to.is_some() {
return Err(Error::conflict());
}
}
Ok(())
}
impl Graph {
#[doc(hidden)]
pub fn begin_constraint_admission(&self) -> ConstraintAdmission<'_> {
let (specs, scope, charges) = {
let index = self.constraint_keys.lock().unwrap();
let specs: BTreeMap<String, AdmissionSpec> = index
.specs()
.map(|spec| {
(
spec.name.clone(),
AdmissionSpec {
spec: spec.clone(),
origin: Origin::Committed,
},
)
})
.collect();
let charges = specs
.keys()
.map(|name| (name.clone(), index.charge_of(name)))
.collect();
(specs, index.scope().clone(), charges)
};
ConstraintAdmission {
graph: self,
specs,
scope,
charges,
names: NameTable::default(),
holds: HashMap::new(),
}
}
}