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::derived_constraints_map(&body.to_body())
85                    .map_err(crate::graph_type::persisted_derive_error)?
86                    .into_iter()
87                    .map(|(name, constraint)| (name, Some(constraint)))
88                    .collect();
89            }
90            RedoOp::CatalogIndexDetail { options, .. } => {
91                redo::props_from_json(options)?;
92            }
93            RedoOp::SetNodeProp { .. }
94            | RedoOp::RemoveNodeProp { .. }
95            | RedoOp::SetRelProp { .. }
96            | RedoOp::RemoveRelProp { .. }
97            | RedoOp::AddLabels { .. }
98            | RedoOp::RemoveLabels { .. }
99            | RedoOp::PutDatabase { .. }
100            | RedoOp::DropDatabase { .. }
101            | RedoOp::PutGraphType { .. }
102            | RedoOp::PullIdentityPut { .. }
103            | RedoOp::OntologySet { .. }
104            | RedoOp::OntologyDrop { .. } => {}
105        }
106        Ok(())
107    }
108
109    fn constraint(&self, name: &str) -> Option<&ConstraintDef> {
110        self.constraints
111            .get(name)
112            .map(Option::as_ref)
113            .unwrap_or_else(|| self.catalog.constraints.get(name))
114    }
115
116    fn derived(&self, name: &str) -> Option<&relate_model::Constraint> {
117        self.derived
118            .get(name)
119            .map(Option::as_ref)
120            .unwrap_or_else(|| {
121                if self.reset_derived {
122                    None
123                } else {
124                    self.derived_baseline.get(name)
125                }
126            })
127    }
128
129    fn node_exists(&self, id: NodeId) -> bool {
130        self.nodes
131            .get(&id)
132            .copied()
133            .unwrap_or_else(|| self.graph.node_visible_at(id, self.base_ts))
134    }
135
136    fn rel_ends(&self, id: RelId) -> Option<(NodeId, NodeId)> {
137        self.rels
138            .get(&id)
139            .copied()
140            .unwrap_or_else(|| self.graph.rel_ends_at(id, self.base_ts))
141    }
142
143    fn detach_node(&mut self, id: NodeId) {
144        self.nodes.insert(id, false);
145        // Include relationships created earlier in this redo, as well as
146        // untouched live adjacency. No property maps or whole-graph copy.
147        for (ends, state) in self
148            .rels
149            .values_mut()
150            .filter_map(|state| state.as_ref().copied().map(|ends| (ends, state)))
151        {
152            if ends.0 == id || ends.1 == id {
153                *state = None;
154            }
155        }
156        for side in [self.graph.out_side(), self.graph.in_side()] {
157            // The merged delta+sealed stream (ADR-0551): copy the hop ids
158            // out under the store guard, then probe `rel_ends`, which takes
159            // the rels store's lock (never re-enter the adjacency store).
160            let mut hops = Vec::new();
161            side.with_adj(id, |by_type, region| {
162                by_type.for_each_hop(region, self.base_ts, |hop| hops.push(hop.id));
163            });
164            for rid in hops {
165                if self.rel_ends(rid).is_some() {
166                    self.rels.insert(rid, None);
167                }
168            }
169        }
170    }
171
172    // Seed only potentially conflicting entries, then let Catalog's own
173    // insertion methods decide idempotency, name and equivalent-schema errors.
174    fn insert_index(&mut self, def: IndexDef) -> Result<()> {
175        let mut candidate = Catalog::default();
176        for existing in self.catalog.indexes.values().filter(|existing| {
177            !self.indexes.contains_key(&existing.name)
178                && (existing.name == def.name
179                    || (existing.label == def.label && existing.property == def.property))
180        }) {
181            candidate
182                .indexes
183                .insert(existing.name.clone(), existing.clone());
184        }
185        for existing in self.indexes.values().flatten().filter(|existing| {
186            existing.name == def.name
187                || (existing.label == def.label && existing.property == def.property)
188        }) {
189            candidate
190                .indexes
191                .insert(existing.name.clone(), existing.clone());
192        }
193        candidate.insert_index(def.clone())?;
194        self.indexes.insert(def.name.clone(), Some(def));
195        Ok(())
196    }
197
198    fn insert_constraint(&mut self, def: ConstraintDef) -> Result<()> {
199        let relevant = |existing: &ConstraintDef| {
200            existing.name == def.name
201                || (existing.relationship == def.relationship
202                    && existing.label == def.label
203                    && existing.properties == def.properties
204                    && existing.kind == def.kind)
205        };
206        let mut candidate = Catalog::default();
207        for existing in
208            self.catalog.constraints.values().filter(|existing| {
209                !self.constraints.contains_key(&existing.name) && relevant(existing)
210            })
211        {
212            candidate
213                .constraints
214                .insert(existing.name.clone(), existing.clone());
215        }
216        for existing in self.constraints.values().flatten().filter(|v| relevant(v)) {
217            candidate
218                .constraints
219                .insert(existing.name.clone(), existing.clone());
220        }
221        candidate.insert_constraint(def.clone())?;
222        self.constraints.insert(def.name.clone(), Some(def));
223        Ok(())
224    }
225}
226
227impl Graph {
228    /// Read-only ordered applicability check for a record against a stable
229    /// graph. The caller serializes it with writers.
230    pub fn validate_redo_applicability(&self, ops: &[RedoOp], commit_ts: u64) -> Result<()> {
231        self.validate_redo_group_applicability(std::iter::once((ops, commit_ts)))
232    }
233
234    /// Validate independent records in commit order against one touched-state
235    /// view, without copying any of the group's property payloads.
236    pub fn validate_redo_group_applicability<'a>(
237        &self,
238        records: impl IntoIterator<Item = (&'a [RedoOp], u64)>,
239    ) -> Result<()> {
240        self.validate_redo_group(records, true)
241    }
242
243    pub(super) fn validate_redo_group<'a>(
244        &self,
245        records: impl IntoIterator<Item = (&'a [RedoOp], u64)>,
246        enforce_new: bool,
247    ) -> Result<()> {
248        let records: Vec<_> = records.into_iter().collect();
249        let derived_baseline = {
250            let theater = self.theater.lock().unwrap();
251            records
252                .iter()
253                .flat_map(|(ops, _)| ops.iter())
254                .filter_map(|op| match op {
255                    RedoOp::CreateConstraint { name, .. } => theater
256                        .derived_constraints
257                        .get(name)
258                        .map(|c| (name.clone(), c.clone())),
259                    _ => None,
260                })
261                .collect()
262        };
263        let catalog = self.catalog.lock().unwrap();
264        let mut state = RedoPreflight {
265            graph: self,
266            catalog: &catalog,
267            base_ts: self.commit_ts(),
268            nodes: HashMap::new(),
269            rels: HashMap::new(),
270            indexes: HashMap::new(),
271            constraints: HashMap::new(),
272            derived: HashMap::new(),
273            derived_baseline,
274            reset_derived: false,
275        };
276        let mut last_ts = state.base_ts;
277        for (ops, commit_ts) in records {
278            if commit_ts == 0 || commit_ts == u64::MAX || commit_ts <= last_ts {
279                return Err(relate_core::Error::storage(format!(
280                    "WAL commit timestamp {commit_ts} must advance past {last_ts} and be below u64::MAX"
281                )));
282            }
283            // Installation checks endpoints at the proposed write timestamp.
284            // Untouched baseline versions must be read at the same timestamp;
285            // touched entries still take precedence in the ordered scratch view.
286            state.base_ts = commit_ts;
287            let mut created = HashSet::new();
288            for op in ops {
289                state.check_op(op)?;
290                if let RedoOp::CreateConstraint { name, .. } = op {
291                    created.insert(name.as_str());
292                }
293            }
294            if enforce_new {
295                for name in created {
296                    if let Some(def) = state
297                        .constraint(name)
298                        .filter(|d| requires_enforced_label(d))
299                    {
300                        if !state
301                            .derived(name)
302                            .is_some_and(|c| matching_enforced_label(def, c))
303                        {
304                            return Err(Error::storage(format!(
305                                "named label constraint {name} is missing matching enforced label"
306                            )));
307                        }
308                    }
309                }
310            }
311            last_ts = commit_ts;
312        }
313        Ok(())
314    }
315}