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 (map, sealed) in [
157            (&self.graph.out_adj, &self.graph.sealed_out),
158            (&self.graph.in_adj, &self.graph.sealed_in),
159        ] {
160            // The merged delta+sealed stream (ADR-0551): copy the hop ids
161            // out under the store guard, then probe `rel_ends`, which takes
162            // the rels store's lock (never re-enter the adjacency store).
163            let mut hops = Vec::new();
164            if let Some(by_type) = map.get(&id) {
165                by_type.for_each_hop(sealed.get(&id).as_deref(), self.base_ts, |hop| {
166                    hops.push(hop.id)
167                });
168            }
169            for rid in hops {
170                if self.rel_ends(rid).is_some() {
171                    self.rels.insert(rid, None);
172                }
173            }
174        }
175    }
176
177    // Seed only potentially conflicting entries, then let Catalog's own
178    // insertion methods decide idempotency, name and equivalent-schema errors.
179    fn insert_index(&mut self, def: IndexDef) -> Result<()> {
180        let mut candidate = Catalog::default();
181        for existing in self.catalog.indexes.values().filter(|existing| {
182            !self.indexes.contains_key(&existing.name)
183                && (existing.name == def.name
184                    || (existing.label == def.label && existing.property == def.property))
185        }) {
186            candidate
187                .indexes
188                .insert(existing.name.clone(), existing.clone());
189        }
190        for existing in self.indexes.values().flatten().filter(|existing| {
191            existing.name == def.name
192                || (existing.label == def.label && existing.property == def.property)
193        }) {
194            candidate
195                .indexes
196                .insert(existing.name.clone(), existing.clone());
197        }
198        candidate.insert_index(def.clone())?;
199        self.indexes.insert(def.name.clone(), Some(def));
200        Ok(())
201    }
202
203    fn insert_constraint(&mut self, def: ConstraintDef) -> Result<()> {
204        let relevant = |existing: &ConstraintDef| {
205            existing.name == def.name
206                || (existing.relationship == def.relationship
207                    && existing.label == def.label
208                    && existing.properties == def.properties
209                    && existing.kind == def.kind)
210        };
211        let mut candidate = Catalog::default();
212        for existing in
213            self.catalog.constraints.values().filter(|existing| {
214                !self.constraints.contains_key(&existing.name) && relevant(existing)
215            })
216        {
217            candidate
218                .constraints
219                .insert(existing.name.clone(), existing.clone());
220        }
221        for existing in self.constraints.values().flatten().filter(|v| relevant(v)) {
222            candidate
223                .constraints
224                .insert(existing.name.clone(), existing.clone());
225        }
226        candidate.insert_constraint(def.clone())?;
227        self.constraints.insert(def.name.clone(), Some(def));
228        Ok(())
229    }
230}
231
232impl Graph {
233    /// Read-only ordered applicability check for a record against a stable
234    /// graph. The caller serializes it with writers.
235    pub fn validate_redo_applicability(&self, ops: &[RedoOp], commit_ts: u64) -> Result<()> {
236        self.validate_redo_group_applicability(std::iter::once((ops, commit_ts)))
237    }
238
239    /// Validate independent records in commit order against one touched-state
240    /// view, without copying any of the group's property payloads.
241    pub fn validate_redo_group_applicability<'a>(
242        &self,
243        records: impl IntoIterator<Item = (&'a [RedoOp], u64)>,
244    ) -> Result<()> {
245        self.validate_redo_group(records, true)
246    }
247
248    pub(super) fn validate_redo_group<'a>(
249        &self,
250        records: impl IntoIterator<Item = (&'a [RedoOp], u64)>,
251        enforce_new: bool,
252    ) -> Result<()> {
253        let records: Vec<_> = records.into_iter().collect();
254        let derived_baseline = {
255            let theater = self.theater.lock().unwrap();
256            records
257                .iter()
258                .flat_map(|(ops, _)| ops.iter())
259                .filter_map(|op| match op {
260                    RedoOp::CreateConstraint { name, .. } => theater
261                        .derived_constraints
262                        .get(name)
263                        .map(|c| (name.clone(), c.clone())),
264                    _ => None,
265                })
266                .collect()
267        };
268        let catalog = self.catalog.lock().unwrap();
269        let mut state = RedoPreflight {
270            graph: self,
271            catalog: &catalog,
272            base_ts: self.commit_ts(),
273            nodes: HashMap::new(),
274            rels: HashMap::new(),
275            indexes: HashMap::new(),
276            constraints: HashMap::new(),
277            derived: HashMap::new(),
278            derived_baseline,
279            reset_derived: false,
280        };
281        let mut last_ts = state.base_ts;
282        for (ops, commit_ts) in records {
283            if commit_ts == 0 || commit_ts == u64::MAX || commit_ts <= last_ts {
284                return Err(relate_core::Error::storage(format!(
285                    "WAL commit timestamp {commit_ts} must advance past {last_ts} and be below u64::MAX"
286                )));
287            }
288            // Installation checks endpoints at the proposed write timestamp.
289            // Untouched baseline versions must be read at the same timestamp;
290            // touched entries still take precedence in the ordered scratch view.
291            state.base_ts = commit_ts;
292            let mut created = HashSet::new();
293            for op in ops {
294                state.check_op(op)?;
295                if let RedoOp::CreateConstraint { name, .. } = op {
296                    created.insert(name.as_str());
297                }
298            }
299            if enforce_new {
300                for name in created {
301                    if let Some(def) = state
302                        .constraint(name)
303                        .filter(|d| requires_enforced_label(d))
304                    {
305                        if !state
306                            .derived(name)
307                            .is_some_and(|c| matching_enforced_label(def, c))
308                        {
309                            return Err(Error::storage(format!(
310                                "named label constraint {name} is missing matching enforced label"
311                            )));
312                        }
313                    }
314                }
315            }
316            last_ts = commit_ts;
317        }
318        Ok(())
319    }
320}