Skip to main content

relate_engine_api/redo/
mod.rs

1//! Physical redo ops for the WAL (ADR-0012). Not Cypher text.
2//!
3//! Catalog-DDL ops (`CatalogIndexDetail`, `PutGraphType`,
4//! `SetCurrentGraphType`) carry typed, serde-serializable payload models
5//! captured once at DDL-execution time. `Graph::apply_redo` stores them
6//! verbatim; it never re-parses Cypher text and never swallows a decode
7//! failure.
8
9use serde::{Deserialize, Serialize};
10
11use relate_catalog::ConstraintDef;
12use relate_core::{NodeId, RelId, Result, Value};
13
14use crate::graph_type::GraphTypeSpec;
15
16// Redo ops carry typed values; the tagged-JSON encoding is canonical on
17// `Value` in relate-core (shared with the Parquet codec). The one cold
18// path that still carries a raw `serde_json::Value` (`CatalogIndexDetail.options`)
19// uses the helpers in `wal_format_json`. Re-exported so callers stay unchanged.
20mod index;
21pub use index::*;
22pub mod wal_format_json;
23pub use wal_format_json::{props_from_json, props_json};
24
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26#[serde(tag = "op")]
27pub enum RedoOp {
28    CreateNode {
29        id: NodeId,
30        labels: std::sync::Arc<Vec<String>>,
31        properties: std::sync::Arc<relate_core::PropertyMap>,
32    },
33    CreateRel {
34        id: RelId,
35        start: NodeId,
36        end: NodeId,
37        rel_type: String,
38        properties: std::sync::Arc<relate_core::PropertyMap>,
39    },
40    DeleteNode {
41        id: NodeId,
42    },
43    DeleteRel {
44        id: RelId,
45    },
46    SetNodeProp {
47        id: NodeId,
48        key: String,
49        value: Value,
50    },
51    RemoveNodeProp {
52        id: NodeId,
53        key: String,
54    },
55    SetRelProp {
56        id: RelId,
57        key: String,
58        value: Value,
59    },
60    RemoveRelProp {
61        id: RelId,
62        key: String,
63    },
64    AddLabels {
65        id: NodeId,
66        labels: Vec<String>,
67    },
68    RemoveLabels {
69        id: NodeId,
70        labels: Vec<String>,
71    },
72    CreateIndex {
73        name: String,
74        label: String,
75        property: String,
76    },
77    DropIndex {
78        name: String,
79    },
80    CreateConstraint {
81        name: String,
82        #[serde(default)]
83        relationship: bool,
84        label: String,
85        properties: Vec<String>,
86        kind: String,
87        #[serde(default)]
88        property_type: Option<String>,
89        /// The label a `labelExistence`/`sourceLabel`/`targetLabel`
90        /// constraint requires to be present (CIP-177, CIP-266), part of the
91        /// constraint's schema identity. `None` for every other kind and for
92        /// rows written before the field existed.
93        #[serde(default, skip_serializing_if = "Option::is_none")]
94        enforced_label: Option<String>,
95    },
96    DropConstraint {
97        name: String,
98    },
99    CatalogIndexDetail {
100        name: String,
101        detail: IndexDetailSpec,
102        /// The evaluated `OPTIONS` map (tagged JSON values, see
103        /// [`props_json`]). Decoded strictly by [`props_from_json`].
104        options: serde_json::Value,
105    },
106    /// SHOW metadata for an explicitly enforced constraint.
107    CatalogDerivedConstraint {
108        constraint: relate_model::Constraint,
109    },
110    PutDatabase {
111        name: String,
112        language: u32,
113        composite: bool,
114    },
115    /// Legacy, decode-only: `DROP DATABASE` was executable before the
116    /// parser failed closed on unsupported administration commands
117    /// (ADR-0116), so WALs and snapshots written by those versions may
118    /// carry this op. New code never constructs it; replay is the
119    /// ADR-0116 §8 no-op (only fixed namespaces exist, and a fixed
120    /// namespace can never be dropped). Removing the variant would make
121    /// serde reject the old record and hard-fail store open (ADR-0114).
122    DropDatabase {
123        name: String,
124    },
125    PutGraphType {
126        name: String,
127        body: GraphTypeSpec,
128    },
129    SetCurrentGraphType {
130        body: GraphTypeSpec,
131    },
132    /// Source-scoped pull identity (ADR-0080). Not a graph CDC event.
133    PullIdentityPut {
134        source: String,
135        kind: PullKind,
136        remote_id: String,
137        local_id: i64,
138    },
139    /// Store-level ontology document ops (ADR-0120 §3). Not graph ops:
140    /// they carry the validated ontology document verbatim (at most one
141    /// per store, for `neo4j`) and mutate no graph or catalog state; the
142    /// derived `system_ontologies` graph is rebuilt from the document.
143    /// The document is bounded by [`MAX_ONTOLOGY_SPEC_BYTES`], checked
144    /// before the commit is written.
145    OntologySet {
146        database: String,
147        spec: String,
148    },
149    OntologyDrop {
150        database: String,
151    },
152}
153
154/// The ADR-0086 object envelope bounding one ontology document
155/// (ADR-0120 §3): 16 MiB, checked before the commit is written.
156pub const MAX_ONTOLOGY_SPEC_BYTES: usize = 16 * 1024 * 1024;
157
158/// Typed view of a store-level ontology document op (ADR-0120 §3), the
159/// classification [`RedoOp::ontology_op`] returns: `Set` borrows the
160/// verbatim document, `Drop` carries nothing. Consumers match this once
161/// instead of re-matching the redo variants.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub enum OntologyOp<'a> {
164    /// `OntologySet`: the verbatim ontology document.
165    Set(&'a str),
166    /// `OntologyDrop`.
167    Drop,
168}
169
170impl RedoOp {
171    /// The [`RedoOp::CreateConstraint`] row for one catalog definition — the
172    /// one crossing from the catalog shape to the durable op shape, so the
173    /// field copies live once ([`RedoOp::constraint_def`] is its reader).
174    pub fn create_constraint(def: ConstraintDef) -> Self {
175        Self::CreateConstraint {
176            name: def.name,
177            relationship: def.relationship,
178            label: def.label,
179            properties: def.properties,
180            kind: def.kind,
181            property_type: def.property_type,
182            enforced_label: def.enforced_label,
183        }
184    }
185
186    /// The catalog definition a `CreateConstraint` row carries, `None` for
187    /// every other op — the reader twin of [`RedoOp::create_constraint`].
188    pub fn constraint_def(&self) -> Option<ConstraintDef> {
189        match self {
190            Self::CreateConstraint {
191                name,
192                relationship,
193                label,
194                properties,
195                kind,
196                property_type,
197                enforced_label,
198            } => Some(ConstraintDef {
199                name: name.clone(),
200                relationship: *relationship,
201                label: label.clone(),
202                properties: properties.clone(),
203                kind: kind.clone(),
204                property_type: property_type.clone(),
205                enforced_label: enforced_label.clone(),
206            }),
207            _ => None,
208        }
209    }
210
211    pub fn create_node(
212        id: NodeId,
213        labels: impl Into<std::sync::Arc<Vec<String>>>,
214        properties: impl Into<relate_core::PropertyMap>,
215    ) -> Self {
216        Self::CreateNode {
217            id,
218            labels: labels.into(),
219            properties: std::sync::Arc::new(properties.into()),
220        }
221    }
222
223    pub fn create_rel(
224        id: RelId,
225        start: NodeId,
226        end: NodeId,
227        rel_type: String,
228        properties: impl Into<relate_core::PropertyMap>,
229    ) -> Self {
230        Self::CreateRel {
231            id,
232            start,
233            end,
234            rel_type,
235            properties: std::sync::Arc::new(properties.into()),
236        }
237    }
238
239    pub fn delete_node(id: NodeId) -> Self {
240        Self::DeleteNode { id }
241    }
242
243    pub fn delete_rel(id: RelId) -> Self {
244        Self::DeleteRel { id }
245    }
246
247    pub fn add_labels(id: NodeId, labels: Vec<String>) -> Self {
248        Self::AddLabels { id, labels }
249    }
250
251    pub fn remove_labels(id: NodeId, labels: Vec<String>) -> Self {
252        Self::RemoveLabels { id, labels }
253    }
254
255    pub fn set_node_prop(id: NodeId, key: String, value: Value) -> Self {
256        Self::SetNodeProp { id, key, value }
257    }
258
259    pub fn remove_node_prop(id: NodeId, key: String) -> Self {
260        Self::RemoveNodeProp { id, key }
261    }
262
263    pub fn set_rel_prop(id: RelId, key: String, value: Value) -> Self {
264        Self::SetRelProp { id, key, value }
265    }
266
267    pub fn remove_rel_prop(id: RelId, key: String) -> Self {
268        Self::RemoveRelProp { id, key }
269    }
270
271    /// The typed ontology classification of this op (ADR-0120 §3); `None`
272    /// for every non-ontology op. One match — [`Self::is_ontology_op`],
273    /// the WAL's `MDBWAL02` segment-magic rule (ADR-0120 §4), the
274    /// scanner's corruption check and the facade's commit scan all derive
275    /// from it.
276    pub fn ontology_op(&self) -> Option<OntologyOp<'_>> {
277        match self {
278            Self::OntologySet { spec, .. } => Some(OntologyOp::Set(spec)),
279            Self::OntologyDrop { .. } => Some(OntologyOp::Drop),
280            _ => None,
281        }
282    }
283
284    /// Whether this is a store-level ontology document op (ADR-0120 §3).
285    /// The WAL uses it for the `MDBWAL02` segment-magic rule (ADR-0120 §4)
286    /// and the scanner for the corruption check; the commit-preflight seam
287    /// uses it for the document-size gate.
288    pub fn is_ontology_op(&self) -> bool {
289        self.ontology_op().is_some()
290    }
291
292    /// The one pre-persist validation entry point, run before writing or
293    /// applying redo: every persisted local ID is in range (the upper
294    /// bound is reserved because installation advances the ID allocator),
295    /// and an `OntologySet` document is within the 16 MiB ADR-0086 object
296    /// envelope (ADR-0120 §3). Non-ontology ops always pass the size arm.
297    pub fn validate_ids(&self) -> Result<()> {
298        fn check(id: i64, what: &str) -> Result<()> {
299            relate_core::validate_persisted_id(id, what)
300        }
301        match self {
302            Self::CreateNode { id, .. }
303            | Self::DeleteNode { id }
304            | Self::SetNodeProp { id, .. }
305            | Self::RemoveNodeProp { id, .. }
306            | Self::AddLabels { id, .. }
307            | Self::RemoveLabels { id, .. } => check(*id, "WAL node"),
308            Self::CreateRel { id, start, end, .. } => {
309                check(*id, "WAL relationship")?;
310                check(*start, "WAL relationship start")?;
311                check(*end, "WAL relationship end")
312            }
313            Self::DeleteRel { id }
314            | Self::SetRelProp { id, .. }
315            | Self::RemoveRelProp { id, .. } => check(*id, "WAL relationship"),
316            Self::PullIdentityPut { local_id, .. } => check(*local_id, "WAL pull identity local"),
317            // ADR-0120 §3: the ontology document is limited to 16 MiB
318            // (the ADR-0086 object envelope), checked before the commit is
319            // written.
320            Self::OntologySet { spec, .. } => {
321                if spec.len() > MAX_ONTOLOGY_SPEC_BYTES {
322                    return Err(relate_core::Error::storage(format!(
323                        "ontology document of {} bytes exceeds the 16 MiB limit",
324                        spec.len()
325                    )));
326                }
327                Ok(())
328            }
329            Self::CreateIndex { .. }
330            | Self::DropIndex { .. }
331            | Self::CreateConstraint { .. }
332            | Self::DropConstraint { .. }
333            | Self::CatalogIndexDetail { .. }
334            | Self::CatalogDerivedConstraint { .. }
335            | Self::PutDatabase { .. }
336            | Self::DropDatabase { .. }
337            | Self::PutGraphType { .. }
338            | Self::SetCurrentGraphType { .. }
339            | Self::OntologyDrop { .. } => Ok(()),
340        }
341    }
342
343    /// Whether this is a catalog op: anything but the ten entity ops,
344    /// `PullIdentityPut` and the store-level ontology ops (ADR-0120 §3).
345    /// The write overlay replays only these when it resolves its
346    /// speculative schema (ADR-0172 §8). Classified once, by
347    /// [`Self::write_target`] (ADR-0173).
348    pub fn is_catalog(&self) -> bool {
349        self.write_target().is_catalog()
350    }
351
352    /// What this op writes, for ADR-0015 conflict classification. Total:
353    /// every variant classifies, so a future op is a compile error here,
354    /// not a silently missed conflict rule; consumers bind every payload
355    /// from the one classification. Crate-internal: the consumer set is
356    /// `graph::conflict`; re-export if a cross-crate consumer appears.
357    pub fn write_target(&self) -> WriteTarget<'_> {
358        match self {
359            Self::CreateNode { id, .. } => WriteTarget::CreatedNode(*id),
360            Self::CreateRel { id, start, end, .. } => WriteTarget::CreatedRel {
361                id: *id,
362                start: *start,
363                end: *end,
364            },
365            Self::DeleteNode { id } => WriteTarget::DeletedNode(*id),
366            Self::DeleteRel { id } => WriteTarget::DeletedRel(*id),
367            Self::SetNodeProp { id, .. }
368            | Self::RemoveNodeProp { id, .. }
369            | Self::AddLabels { id, .. }
370            | Self::RemoveLabels { id, .. } => WriteTarget::MutatedNode(*id),
371            Self::SetRelProp { id, .. } | Self::RemoveRelProp { id, .. } => {
372                WriteTarget::MutatedRel(*id)
373            }
374            Self::CreateIndex {
375                name,
376                label,
377                property,
378            } => WriteTarget::CreateIndex {
379                name,
380                label,
381                property,
382            },
383            Self::DropIndex { name } => WriteTarget::DropIndex { name },
384            Self::CreateConstraint { name, .. } => WriteTarget::CreateConstraint { name },
385            Self::DropConstraint { name } => WriteTarget::DropConstraint { name },
386            Self::CatalogIndexDetail { .. }
387            | Self::CatalogDerivedConstraint { .. }
388            | Self::PutDatabase { .. }
389            | Self::DropDatabase { .. }
390            | Self::PutGraphType { .. }
391            | Self::SetCurrentGraphType { .. } => WriteTarget::CatalogMeta,
392            Self::PullIdentityPut { .. } => WriteTarget::PullIdentity,
393            Self::OntologySet { .. } | Self::OntologyDrop { .. } => WriteTarget::Ontology,
394        }
395    }
396
397    /// Every catalog name this op mentions — a label, a relationship type or
398    /// a property key — for the write overlay's catalog facts (ADR-0363
399    /// decision 5): the redo log is the scratch's one write record, so a name
400    /// a transaction has mentioned is known before the commit publishes it.
401    ///
402    /// Total over the enum: every variant classifies, and a new variant is a
403    /// compile error here, never a silently skipped name. Monotone, like the
404    /// committed catalog: an op that removes a name still mentions it — a
405    /// `RemoveLabels` reads exactly like an `AddLabels`, a property `REMOVE`
406    /// like a `SET` — because a name outlives its last write. A drop names
407    /// only its schema object (an index or constraint name), never the label
408    /// or key it was built on, so it cannot un-name one either.
409    ///
410    /// The names are the graph catalog's. Two DDL families name them without
411    /// writing data: an index or constraint create names its subject label
412    /// (or relationship type) and its property keys, and the typed index
413    /// detail names every indexed property plus a vector index's `WITH`
414    /// keys. `CreateIndex.property` carries the legacy `{props}#{KIND}#{name}`
415    /// encoding on the constraint-backed rows (and a bare name on the IR
416    /// path), so its head is the key
417    /// ([`split_legacy_property_encoding`]). Store metadata — index,
418    /// constraint, database, graph-type and ontology names — is not a graph
419    /// catalog name and contributes nothing.
420    pub fn catalog_names(&self) -> Vec<CatalogName<'_>> {
421        /// Append `names` as mentions built by `mention`.
422        fn push<'a>(
423            out: &mut Vec<CatalogName<'a>>,
424            names: impl IntoIterator<Item = &'a String>,
425            mention: fn(&'a str) -> CatalogName<'a>,
426        ) {
427            out.extend(names.into_iter().map(|name| mention(name)));
428        }
429
430        match self {
431            Self::CreateNode {
432                labels, properties, ..
433            } => {
434                let mut names = Vec::with_capacity(labels.len() + properties.len());
435                push(&mut names, labels.iter(), CatalogName::Label);
436                push(&mut names, properties.keys(), CatalogName::PropertyKey);
437                names
438            }
439            Self::CreateRel {
440                rel_type,
441                properties,
442                ..
443            } => {
444                let mut names = Vec::with_capacity(1 + properties.len());
445                names.push(CatalogName::RelType(rel_type));
446                push(&mut names, properties.keys(), CatalogName::PropertyKey);
447                names
448            }
449            Self::SetNodeProp { key, .. }
450            | Self::RemoveNodeProp { key, .. }
451            | Self::SetRelProp { key, .. }
452            | Self::RemoveRelProp { key, .. } => vec![CatalogName::PropertyKey(key)],
453            Self::AddLabels { labels, .. } | Self::RemoveLabels { labels, .. } => {
454                let mut names = Vec::with_capacity(labels.len());
455                push(&mut names, labels.iter(), CatalogName::Label);
456                names
457            }
458            Self::CreateIndex {
459                label, property, ..
460            } => vec![
461                CatalogName::Label(label),
462                CatalogName::PropertyKey(split_legacy_property_encoding(property).0),
463            ],
464            Self::CreateConstraint {
465                relationship,
466                label,
467                properties,
468                ..
469            } => {
470                let mut names = Vec::with_capacity(1 + properties.len());
471                names.push(if *relationship {
472                    CatalogName::RelType(label)
473                } else {
474                    CatalogName::Label(label)
475                });
476                push(&mut names, properties.iter(), CatalogName::PropertyKey);
477                names
478            }
479            Self::CatalogIndexDetail { detail, .. } => {
480                let mut names = Vec::with_capacity(
481                    detail.labels.len() + detail.properties.len() + detail.with_properties.len(),
482                );
483                if detail.relationship {
484                    push(&mut names, detail.labels.iter(), CatalogName::RelType);
485                } else {
486                    push(&mut names, detail.labels.iter(), CatalogName::Label);
487                }
488                push(
489                    &mut names,
490                    detail.properties.iter(),
491                    CatalogName::PropertyKey,
492                );
493                push(
494                    &mut names,
495                    detail.with_properties.iter(),
496                    CatalogName::PropertyKey,
497                );
498                names
499            }
500            Self::CatalogDerivedConstraint { constraint } => {
501                // The op is only constructed from a `Constraint` whose
502                // `entity_type` is `EntityKind::display_name()`, and replay
503                // rejects any other spelling (the same classification
504                // `graph_type::validate` applies to a stored constraint).
505                let relationship =
506                    relate_model::EntityKind::from_display_name(&constraint.entity_type)
507                        == Some(relate_model::EntityKind::Relationship);
508                let mut names = Vec::with_capacity(2 + constraint.properties.len());
509                names.push(if relationship {
510                    CatalogName::RelType(&constraint.label)
511                } else {
512                    CatalogName::Label(&constraint.label)
513                });
514                // An enforced label is always a node label, including on a
515                // relationship constraint (`sourceLabel`/`targetLabel` name
516                // the endpoint's label).
517                if let Some(enforced) = &constraint.enforced_label {
518                    names.push(CatalogName::Label(enforced));
519                }
520                push(
521                    &mut names,
522                    constraint.properties.iter(),
523                    CatalogName::PropertyKey,
524                );
525                names
526            }
527            // A delete names no catalog name, and a drop names only its own
528            // schema object — never the label or key it was built on.
529            Self::DeleteNode { .. }
530            | Self::DeleteRel { .. }
531            | Self::DropIndex { .. }
532            | Self::DropConstraint { .. } => Vec::new(),
533            // Store metadata, not graph catalog names: database names, the
534            // graph-type schema, a pull identity, an ontology document.
535            Self::PutDatabase { .. }
536            | Self::DropDatabase { .. }
537            | Self::PutGraphType { .. }
538            | Self::SetCurrentGraphType { .. }
539            | Self::PullIdentityPut { .. }
540            | Self::OntologySet { .. }
541            | Self::OntologyDrop { .. } => Vec::new(),
542        }
543    }
544}
545
546/// What an op writes (ADR-0015 conflict classification). Total over
547/// [`RedoOp`]: a delete is also a mutation of the same element,
548/// `CreatedRel` carries the endpoints, and catalog ops carry their
549/// (borrowed) identity — consumers match once and bind everything from the
550/// classification.
551#[derive(Debug, Clone, Copy, PartialEq, Eq)]
552pub enum WriteTarget<'a> {
553    CreatedNode(NodeId),
554    CreatedRel {
555        id: RelId,
556        start: NodeId,
557        end: NodeId,
558    },
559    DeletedNode(NodeId),
560    DeletedRel(RelId),
561    MutatedNode(NodeId),
562    MutatedRel(RelId),
563    CreateIndex {
564        name: &'a str,
565        label: &'a str,
566        property: &'a str,
567    },
568    DropIndex {
569        name: &'a str,
570    },
571    CreateConstraint {
572        name: &'a str,
573    },
574    DropConstraint {
575        name: &'a str,
576    },
577    /// Store/catalog metadata mutation (index details, derived
578    /// constraints, databases, graph type).
579    CatalogMeta,
580    /// Source-scoped pull identity (ADR-0080); not a graph CDC event.
581    PullIdentity,
582    /// Store-level ontology document (ADR-0120 §3): not a graph op and not
583    /// catalog metadata, so it conflicts with nothing at the graph layer.
584    Ontology,
585}
586
587impl WriteTarget<'_> {
588    /// Whether the classified op changes the catalog (indexes, constraints,
589    /// store metadata) rather than an entity or a pull identity. Total, so
590    /// a new target must be placed on one side.
591    pub fn is_catalog(&self) -> bool {
592        match self {
593            WriteTarget::CreatedNode(_)
594            | WriteTarget::CreatedRel { .. }
595            | WriteTarget::DeletedNode(_)
596            | WriteTarget::DeletedRel(_)
597            | WriteTarget::MutatedNode(_)
598            | WriteTarget::MutatedRel(_)
599            | WriteTarget::PullIdentity
600            | WriteTarget::Ontology => false,
601            WriteTarget::CreateIndex { .. }
602            | WriteTarget::DropIndex { .. }
603            | WriteTarget::CreateConstraint { .. }
604            | WriteTarget::DropConstraint { .. }
605            | WriteTarget::CatalogMeta => true,
606        }
607    }
608}
609
610/// One catalog name a [`RedoOp`] mentions ([`RedoOp::catalog_names`]), in
611/// the namespace it belongs to. Borrowed from the op — the derivation never
612/// copies a name.
613#[derive(Debug, Clone, Copy, PartialEq, Eq)]
614pub enum CatalogName<'a> {
615    Label(&'a str),
616    RelType(&'a str),
617    PropertyKey(&'a str),
618}
619
620/// Node vs relationship for [`RedoOp::PullIdentityPut`].
621#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
622#[serde(rename_all = "lowercase")]
623pub enum PullKind {
624    Node,
625    Rel,
626}
627
628#[cfg(test)]
629mod tests;