relate-executor 1.0.1

In-memory graph and Cypher physical executor
Documentation
use super::*;

impl Graph {
    pub fn apply_redo(&self, ops: Vec<RedoOp>, commit_ts: u64) -> Result<()> {
        self.apply_redo_inner(ops, commit_ts, false)
    }

    /// Replay historical WAL under the old admission policy, preserving unknown
    /// enforcement as legacy rather than inventing a typed checkpoint image.
    #[doc(hidden)]
    pub fn apply_replayed_redo(&self, ops: Vec<RedoOp>, commit_ts: u64) -> Result<()> {
        self.apply_redo_inner(ops, commit_ts, true)
    }

    pub(super) fn apply_redo_inner(
        &self,
        ops: Vec<RedoOp>,
        commit_ts: u64,
        legacy_replay: bool,
    ) -> Result<()> {
        self.validate_redo_group(std::iter::once((ops.as_slice(), commit_ts)), !legacy_replay)?;
        let legacy_created = if legacy_replay {
            ops.iter()
                .any(|op| matches!(op, RedoOp::CreateConstraint { .. }))
        } else {
            false
        };
        self.in_write.store(true, Ordering::Release);
        self.write_ts.store(commit_ts, Ordering::Release);
        self.record_redo.store(false, Ordering::Release);
        for op in ops {
            match op {
                RedoOp::CreateNode {
                    id,
                    labels,
                    properties,
                } => {
                    // Move the typed fields in — the caller consumed the WAL
                    // borrow before apply, so no clone is needed (ADR-0078).
                    self.install_node(
                        id,
                        std::sync::Arc::unwrap_or_clone(labels),
                        std::sync::Arc::unwrap_or_clone(properties).into(),
                    )?;
                }
                RedoOp::CreateRel {
                    id,
                    start,
                    end,
                    rel_type,
                    properties,
                } => {
                    self.install_rel(
                        id,
                        start,
                        end,
                        rel_type,
                        std::sync::Arc::unwrap_or_clone(properties).into(),
                    )?;
                }
                RedoOp::DeleteNode { id } => {
                    self.delete_node(id, true)?;
                    self.drop_pull_identity(PullKind::Node, id);
                }
                RedoOp::DeleteRel { id } => {
                    self.delete_rel(id);
                    self.drop_pull_identity(PullKind::Rel, id);
                }
                RedoOp::SetNodeProp { id, key, value } => {
                    self.set_property_node(id, &key, value);
                }
                RedoOp::RemoveNodeProp { id, key } => {
                    self.set_property_node(id, &key, Value::Null);
                }
                RedoOp::SetRelProp { id, key, value } => {
                    self.set_property_rel(id, &key, value);
                }
                RedoOp::RemoveRelProp { id, key } => {
                    self.set_property_rel(id, &key, Value::Null);
                }
                RedoOp::AddLabels { id, labels } => {
                    self.add_labels(id, &labels);
                }
                RedoOp::RemoveLabels { id, labels } => {
                    self.remove_labels(id, &labels);
                }
                RedoOp::CreateIndex {
                    name,
                    label,
                    property,
                } => {
                    self.install_named_index(IndexDef {
                        name,
                        label,
                        property,
                    })?;
                }
                RedoOp::DropIndex { name } => {
                    self.catalog.lock().unwrap().drop_index(&name);
                    let removed = {
                        let mut theater = self.theater.lock().unwrap();
                        theater.index_options.remove(&name);
                        theater.index_details.remove(&name)
                    };
                    if let Some(detail) = removed {
                        self.drop_detail(&detail);
                        self.refresh_index_charge();
                        self.recompute_used();
                    }
                }
                RedoOp::CreateConstraint {
                    name,
                    relationship,
                    label,
                    properties,
                    kind,
                    property_type,
                    enforced_label,
                } => {
                    let def = ConstraintDef {
                        name,
                        relationship,
                        label,
                        properties,
                        kind,
                        property_type,
                        enforced_label,
                    };
                    // ADR-0439: a uniqueness constraint backfills its
                    // committed tuple map from the live graph. The catalog
                    // validates the kind first (its vocabulary is closed), so
                    // the spec builds before the insert moves the def.
                    let spec = super::constraint_keys::spec_from_def(&self.interner, &def);
                    self.catalog.lock().unwrap().insert_constraint(def)?;
                    if let Some(spec) = spec {
                        self.constraint_keys_install(spec);
                    }
                }
                RedoOp::DropConstraint { name } => {
                    self.catalog.lock().unwrap().drop_constraint(&name);
                    self.theater
                        .lock()
                        .unwrap()
                        .derived_constraints
                        .remove(&name);
                    self.legacy_unenforced.lock().unwrap().remove(&name);
                    self.constraint_keys_drop(&name);
                }
                RedoOp::CatalogDerivedConstraint { constraint } => {
                    if let Some(enforced) = &constraint.enforced_label {
                        // An enforced label is always a node label (even on a
                        // relationship constraint, `sourceLabel`/`targetLabel`
                        // name the endpoint's label).
                        self.record_schema_names(false, std::iter::once(enforced.clone()));
                    }
                    if self
                        .catalog
                        .lock()
                        .unwrap()
                        .constraints
                        .get(&constraint.name)
                        .is_some_and(|def| matching_enforced_label(def, &constraint))
                    {
                        self.legacy_unenforced
                            .lock()
                            .unwrap()
                            .remove(&constraint.name);
                    }
                    self.theater
                        .lock()
                        .unwrap()
                        .derived_constraints
                        .insert(constraint.name.clone(), constraint);
                    // No install here: the load-bearing invariant is that
                    // no durable image carries a uniqueness kind in this
                    // record. Witness 1: its only production constructor
                    // (the CREATE CONSTRAINT push) is gated on
                    // `enforced_label`. Witness 2: the parser sets that
                    // field only on `nodeLabelExistence` /
                    // `sourceLabelExistence` / `targetLabelExistence`.
                    // Derived uniqueness reachable via `SetCurrentGraphType`
                    // is the theater half of `uniqueness_specs`;
                    // `rebuild_constraint_keys` covers it.
                }
                RedoOp::CatalogIndexDetail {
                    name,
                    detail,
                    options,
                } => {
                    // Decode before mutating: a corrupted op is an error,
                    // never a silently dropped index detail/options entry.
                    let options = redo::props_from_json(&options)?;
                    // The typed detail is the only op that knows whether its
                    // labels are node labels or relationship types; the
                    // catalog's `CreateIndex` row is entity-kind-blind.
                    self.record_schema_names(detail.relationship, detail.labels.iter().cloned());
                    {
                        let mut theater = self.theater.lock().unwrap();
                        theater.index_details.insert(name.clone(), detail.clone());
                        theater.index_options.insert(name, options);
                    }
                    self.refresh_index_charge();
                    self.materialize_detail(&detail);
                    self.recompute_used();
                }
                RedoOp::PutDatabase {
                    name,
                    language,
                    composite,
                } => {
                    // ADR-0276: the databases catalog is store-level,
                    // shared by every namespace graph; per the ADR-0116 §8
                    // invariants only the fixed namespaces are kept,
                    // replayed entries for other names are ignored.
                    self.databases().put_database(&name, language, composite);
                }
                RedoOp::DropDatabase { .. } => {
                    // ADR-0116 §1/§8: the fixed namespaces cannot be
                    // dropped, and the `Namespace`-keyed catalog can only
                    // ever hold them, so a legacy `DROP DATABASE` redo is
                    // a no-op.
                }
                RedoOp::PutGraphType { name, body } => {
                    self.theater.lock().unwrap().graph_types.insert(name, body);
                }
                RedoOp::SetCurrentGraphType { body } => {
                    let (previous, derived) = {
                        let mut theater = self.theater.lock().unwrap();
                        let previous = theater.derived_constraints.clone();
                        super::theater::set_current_graph_type(&mut theater, &body)?;
                        (previous, theater.derived_constraints.clone())
                    };
                    // A record written before a generated-name or derivation
                    // change installs rows under names this binary no longer
                    // derives. Re-keying them here is what keeps a replayed
                    // store's catalog equal to its re-derived index (a stale
                    // row would otherwise survive every purge and turn the
                    // next `ALTER CURRENT GRAPH TYPE` into a conflict). This
                    // record replaces the set wholesale — the statement's own
                    // purge already dropped every record it named — so a
                    // record the new derivation does not produce goes. Each
                    // half runs under its own lock: schema capture takes the
                    // catalog without waiting for the theater, so no path may
                    // hold both.
                    let migration = (!previous.is_empty() && previous != derived).then(|| {
                        super::derived_migration::plan_derived_migration(
                            &previous,
                            &derived,
                            super::derived_migration::UnmatchedRecords::Drop,
                        )
                    });
                    let installed = match &migration {
                        Some(migration) => {
                            migration.apply_to_theater(&mut self.theater.lock().unwrap());
                            migration.apply_to_catalog(&mut self.catalog.lock().unwrap())?
                        }
                        None => Vec::new(),
                    };
                    {
                        let catalog = self.catalog.lock().unwrap();
                        self.legacy_unenforced.lock().unwrap().retain(|name, _| {
                            !catalog.constraints.get(name).is_some_and(|def| {
                                derived.get(name).is_some_and(|constraint| {
                                    matching_enforced_label(def, constraint)
                                })
                            })
                        });
                    }
                    if let Some(migration) = migration {
                        migration
                            .install_theater_details(&mut self.theater.lock().unwrap(), &installed);
                        self.refresh_index_charge();
                        self.recompute_used();
                    }
                    // ADR-0439: this arm is the constraint-key map's fourth
                    // rebuild trigger. The derived set was just replaced
                    // wholesale from the persisted body, and the per-op row
                    // stream does not mirror it in every reachable shape:
                    // a legacy replay record may carry `SetCurrentGraphType`
                    // alone, without the `CreateConstraint` rows a current
                    // statement emits first, and a current statement's
                    // `sync_derived_constraints` skips a derived constraint
                    // that is schema-equivalent to a surviving catalog one,
                    // so that derived name has no row either. Rebuild from
                    // the committed catalog + the re-derived set so the map
                    // still covers both.
                    self.rebuild_constraint_keys();
                }
                RedoOp::PullIdentityPut {
                    source,
                    kind,
                    remote_id,
                    local_id,
                } => {
                    self.pull_identity_put(source, kind, remote_id, local_id);
                }
                RedoOp::OntologySet { .. } | RedoOp::OntologyDrop { .. } => {
                    // ADR-0120 §2/§3: store-level ops; they carry no graph
                    // mutation. The document lives with the store layer —
                    // no graph is derived from it (ADR-0229 §3) — so replay
                    // is a deliberate no-op here.
                }
            }
        }
        self.pending_redo.lock().unwrap().clear();
        self.set_commit_ts(commit_ts);
        self.in_write.store(false, Ordering::Release);
        self.record_redo.store(true, Ordering::Release);
        if legacy_created {
            self.mark_legacy_unenforced();
        }
        Ok(())
    }
}