Skip to main content

relate_executor/graph/
redo_preflight.rs

1//! Ordered redo applicability preflight: a read-only state machine that checks
2//! each record's operations against the live graph and earlier records in the
3//! same group, without copying property payloads.
4
5use std::collections::{HashMap, HashSet};
6
7use relate_catalog::{Catalog, ConstraintDef, IndexDef};
8use relate_core::{Error, NodeId, RelId, Result};
9
10use crate::redo::{self, RedoOp};
11
12use super::{matching_enforced_label, requires_enforced_label, Graph};
13
14/// Only IDs and catalog names touched by the ordered redo are stored here.
15/// The live graph and catalog remain the read-only baseline for untouched keys.
16struct RedoPreflight<'a> {
17    graph: &'a Graph,
18    catalog: &'a Catalog,
19    base_ts: u64,
20    nodes: HashMap<NodeId, bool>,
21    rels: HashMap<RelId, Option<(NodeId, NodeId)>>,
22    indexes: HashMap<String, Option<IndexDef>>,
23    constraints: HashMap<String, Option<ConstraintDef>>,
24    derived: HashMap<String, Option<relate_model::Constraint>>,
25    derived_baseline: HashMap<String, relate_model::Constraint>,
26    reset_derived: bool,
27}
28
29impl RedoPreflight<'_> {
30    fn check_op(&mut self, op: &RedoOp) -> Result<()> {
31        op.validate_ids()?;
32        // The constraint row is one shape: fold its def first, so no arm
33        // re-derives or expect-guards it.
34        if let Some(def) = op.constraint_def() {
35            return self.insert_constraint(def);
36        }
37        match op {
38            RedoOp::CreateNode { id, .. } => {
39                self.nodes.insert(*id, true);
40            }
41            RedoOp::CreateRel { id, start, end, .. } => {
42                if !self.node_exists(*start) || !self.node_exists(*end) {
43                    return Err(super::missing_rel_endpoint_error());
44                }
45                self.rels.insert(*id, Some((*start, *end)));
46            }
47            RedoOp::DeleteNode { id } => self.detach_node(*id),
48            RedoOp::DeleteRel { id } => {
49                self.rels.insert(*id, None);
50            }
51            RedoOp::CreateIndex {
52                name,
53                label,
54                property,
55            } => {
56                self.insert_index(IndexDef {
57                    name: name.clone(),
58                    label: label.clone(),
59                    property: property.clone(),
60                })?;
61            }
62            RedoOp::DropIndex { name } => {
63                self.indexes.insert(name.clone(), None);
64            }
65            // Handled by the def fold above; listed for exhaustiveness.
66            RedoOp::CreateConstraint { .. } => {}
67            RedoOp::DropConstraint { name } => {
68                self.constraints.insert(name.clone(), None);
69                self.derived.insert(name.clone(), None);
70            }
71            RedoOp::CatalogDerivedConstraint { constraint } => {
72                // A WAL record can carry any `entity_type` string: a value
73                // naming neither kind is corruption, and the typed error here
74                // (the same fail-loud-not-panic rule as `set_current_graph_type`
75                // above) is what turns it into a typed storage error — the
76                // classification itself (`entity_kind`) is total and never
77                // panics, so every pre-preflight seam stays panic-free too.
78                constraint.entity_kind().map_err(Error::storage)?;
79                self.derived
80                    .insert(constraint.name.clone(), Some(constraint.clone()));
81            }
82            RedoOp::SetCurrentGraphType { body } => {
83                self.reset_derived = true;
84                self.derived = crate::graph_type::persisted_derived_map(body)?
85                    .into_iter()
86                    .map(|(name, constraint)| (name, Some(constraint)))
87                    .collect();
88            }
89            RedoOp::CatalogIndexDetail { options, .. } => {
90                redo::props_from_json(options)?;
91            }
92            RedoOp::SetNodeProp { .. }
93            | RedoOp::RemoveNodeProp { .. }
94            | RedoOp::SetRelProp { .. }
95            | RedoOp::RemoveRelProp { .. }
96            | RedoOp::AddLabels { .. }
97            | RedoOp::RemoveLabels { .. }
98            | RedoOp::PutDatabase { .. }
99            | RedoOp::DropDatabase { .. }
100            | RedoOp::PutGraphType { .. }
101            | RedoOp::PullIdentityPut { .. }
102            | RedoOp::OntologySet { .. }
103            | RedoOp::OntologyDrop { .. } => {}
104        }
105        Ok(())
106    }
107
108    fn constraint(&self, name: &str) -> Option<&ConstraintDef> {
109        self.constraints
110            .get(name)
111            .map(Option::as_ref)
112            .unwrap_or_else(|| self.catalog.constraints.get(name))
113    }
114
115    fn derived(&self, name: &str) -> Option<&relate_model::Constraint> {
116        self.derived
117            .get(name)
118            .map(Option::as_ref)
119            .unwrap_or_else(|| {
120                if self.reset_derived {
121                    None
122                } else {
123                    self.derived_baseline.get(name)
124                }
125            })
126    }
127
128    fn node_exists(&self, id: NodeId) -> bool {
129        self.nodes
130            .get(&id)
131            .copied()
132            .unwrap_or_else(|| self.graph.node_visible_at(id, self.base_ts))
133    }
134
135    fn rel_ends(&self, id: RelId) -> Option<(NodeId, NodeId)> {
136        self.rels
137            .get(&id)
138            .copied()
139            .unwrap_or_else(|| self.graph.rel_ends_at(id, self.base_ts))
140    }
141
142    fn detach_node(&mut self, id: NodeId) {
143        self.nodes.insert(id, false);
144        // Include relationships created earlier in this redo, as well as
145        // untouched live adjacency. No property maps or whole-graph copy.
146        for (ends, state) in self
147            .rels
148            .values_mut()
149            .filter_map(|state| state.as_ref().copied().map(|ends| (ends, state)))
150        {
151            if ends.0 == id || ends.1 == id {
152                *state = None;
153            }
154        }
155        for side in [self.graph.out_side(), self.graph.in_side()] {
156            // The merged delta+sealed stream (ADR-0551): copy the hop ids
157            // out under the store guard, then probe `rel_ends`, which takes
158            // the rels store's lock (never re-enter the adjacency store).
159            let mut hops = Vec::new();
160            side.with_adj(id, |by_type, region| {
161                by_type.for_each_hop(region, self.base_ts, |hop| hops.push(hop.id));
162            });
163            for rid in hops {
164                if self.rel_ends(rid).is_some() {
165                    self.rels.insert(rid, None);
166                }
167            }
168        }
169    }
170
171    // Seed only potentially conflicting entries, then let Catalog's own
172    // insertion methods decide idempotency, name and equivalent-schema errors.
173    fn insert_index(&mut self, def: IndexDef) -> Result<()> {
174        let mut candidate = Catalog::default();
175        for existing in self.catalog.indexes.values().filter(|existing| {
176            !self.indexes.contains_key(&existing.name)
177                && (existing.name == def.name
178                    || (existing.label == def.label && existing.property == def.property))
179        }) {
180            candidate
181                .indexes
182                .insert(existing.name.clone(), existing.clone());
183        }
184        for existing in self.indexes.values().flatten().filter(|existing| {
185            existing.name == def.name
186                || (existing.label == def.label && existing.property == def.property)
187        }) {
188            candidate
189                .indexes
190                .insert(existing.name.clone(), existing.clone());
191        }
192        candidate.insert_index(def.clone())?;
193        self.indexes.insert(def.name.clone(), Some(def));
194        Ok(())
195    }
196
197    fn insert_constraint(&mut self, def: ConstraintDef) -> Result<()> {
198        let relevant = |existing: &ConstraintDef| {
199            existing.name == def.name
200                || (existing.relationship == def.relationship
201                    && existing.label == def.label
202                    && existing.properties == def.properties
203                    && existing.kind == def.kind)
204        };
205        let mut candidate = Catalog::default();
206        for existing in
207            self.catalog.constraints.values().filter(|existing| {
208                !self.constraints.contains_key(&existing.name) && relevant(existing)
209            })
210        {
211            candidate
212                .constraints
213                .insert(existing.name.clone(), existing.clone());
214        }
215        for existing in self.constraints.values().flatten().filter(|v| relevant(v)) {
216            candidate
217                .constraints
218                .insert(existing.name.clone(), existing.clone());
219        }
220        candidate.insert_constraint(def.clone())?;
221        self.constraints.insert(def.name.clone(), Some(def));
222        Ok(())
223    }
224}
225
226impl Graph {
227    /// Read-only ordered applicability check for a record against a stable
228    /// graph. The caller serializes it with writers.
229    pub fn validate_redo_applicability(&self, ops: &[RedoOp], commit_ts: u64) -> Result<()> {
230        self.validate_redo_group_applicability(std::iter::once((ops, commit_ts)))
231    }
232
233    /// Validate independent records in commit order against one touched-state
234    /// view, without copying any of the group's property payloads.
235    pub fn validate_redo_group_applicability<'a>(
236        &self,
237        records: impl IntoIterator<Item = (&'a [RedoOp], u64)>,
238    ) -> Result<()> {
239        self.validate_redo_group(records, true)
240    }
241
242    pub(super) fn validate_redo_group<'a>(
243        &self,
244        records: impl IntoIterator<Item = (&'a [RedoOp], u64)>,
245        enforce_new: bool,
246    ) -> Result<()> {
247        let records: Vec<_> = records.into_iter().collect();
248        let derived_baseline = {
249            let theater = self.theater.lock().unwrap();
250            records
251                .iter()
252                .flat_map(|(ops, _)| ops.iter())
253                .filter_map(|op| match op {
254                    RedoOp::CreateConstraint { name, .. } => theater
255                        .derived_constraints
256                        .get(name)
257                        .map(|c| (name.clone(), c.clone())),
258                    _ => None,
259                })
260                .collect()
261        };
262        let catalog = self.catalog.lock().unwrap();
263        let mut state = RedoPreflight {
264            graph: self,
265            catalog: &catalog,
266            base_ts: self.commit_ts(),
267            nodes: HashMap::new(),
268            rels: HashMap::new(),
269            indexes: HashMap::new(),
270            constraints: HashMap::new(),
271            derived: HashMap::new(),
272            derived_baseline,
273            reset_derived: false,
274        };
275        let mut last_ts = state.base_ts;
276        for (ops, commit_ts) in records {
277            if commit_ts == 0 || commit_ts == u64::MAX || commit_ts <= last_ts {
278                return Err(relate_core::Error::storage(format!(
279                    "WAL commit timestamp {commit_ts} must advance past {last_ts} and be below u64::MAX"
280                )));
281            }
282            // Installation checks endpoints at the proposed write timestamp.
283            // Untouched baseline versions must be read at the same timestamp;
284            // touched entries still take precedence in the ordered scratch view.
285            state.base_ts = commit_ts;
286            let mut created = HashSet::new();
287            for op in ops {
288                state.check_op(op)?;
289                if let RedoOp::CreateConstraint { name, .. } = op {
290                    created.insert(name.as_str());
291                }
292            }
293            if enforce_new {
294                for name in created {
295                    if let Some(def) = state
296                        .constraint(name)
297                        .filter(|d| requires_enforced_label(d))
298                    {
299                        if !state
300                            .derived(name)
301                            .is_some_and(|c| matching_enforced_label(def, c))
302                        {
303                            return Err(Error::storage(format!(
304                                "named label constraint {name} is missing matching enforced label"
305                            )));
306                        }
307                    }
308                }
309            }
310            last_ts = commit_ts;
311        }
312        Ok(())
313    }
314}