Skip to main content

relate_executor/graph/
entity_mutation.rs

1//! The entity-mutation family every cross-cutting feature hooks: the create /
2//! install / copy-on-write / property-edit / delete seams for nodes and
3//! relationships, in their own impl-block file (the `label_mutation.rs` and
4//! `degree_stats.rs` precedent, a sibling of the graph family). `Graph`
5//! (graph/mod.rs) keeps the struct and the family-independent plumbing
6//! (ids, pins, charging, catalog reads); the seams that install a version,
7//! maintain the indexes/adjacency/counts, and push redo live here.
8
9use std::ops::ControlFlow;
10
11use super::id_vec::IdVec;
12use super::*;
13use crate::adjacency::Supersede;
14
15impl Graph {
16    pub fn create_node(
17        &self,
18        labels: Vec<String>,
19        properties: BTreeMap<String, Value>,
20    ) -> Result<NodeId> {
21        let id = self.alloc_node_id()?;
22        self.install_node(id, labels, properties)?;
23        Ok(id)
24    }
25
26    pub(in crate::graph) fn install_node(
27        &self,
28        id: NodeId,
29        labels: Vec<String>,
30        properties: BTreeMap<String, Value>,
31    ) -> Result<()> {
32        let next = checked_persisted_id(id, "node")?;
33        self.next_node_id.fetch_max(next, Ordering::Relaxed);
34        self.catalog
35            .lock()
36            .unwrap()
37            .record_labels(labels.iter().cloned());
38        self.bump_stats(|s| {
39            s.nodes_created += 1;
40            s.labels_added += labels.len() as i64;
41            s.properties_set += properties.len() as i64;
42        });
43        if self.recording() {
44            self.push_redo(RedoOp::create_node(
45                id,
46                std::sync::Arc::new(labels.clone()),
47                properties.clone(),
48            ));
49        }
50        let xmin = self.xmin_for_install();
51        let live = LiveNode::from_parts(&self.interner, labels, properties);
52        // ADR-0687: a create's report rule — its label ids only, the
53        // property keys covered by the label stamp (`token_changes`'s
54        // "what a seam reports").
55        self.note_changed_tokens(live.labels.iter().copied());
56        let charge =
57            crate::memory::live_node_account_live(&live, &self.interner, &self.index_charge());
58        // LABS-370 (v1 follow-up) / LABS-851: the exact label counts
59        // and the total node count follow every create, before the
60        // version owns the live set — the node-liveness seam's one
61        // call.
62        self.bump_node_population_stats(&live.labels, CountDelta::Add);
63        // ADR-0439: a created node introduces its constrained tuple(s); a
64        // replay that re-creates an id frees the previous live tuple first.
65        // The map's scope decides whether the node can change any tuple.
66        let edit = self.tracked_node_edit(id, |scope| {
67            scope.touches_node(&live.labels, live.props.iter().map(|(kid, _)| kid))
68        });
69        self.finish_node_edit(edit, id, Some(&live));
70        let before_shape = self.node_chain_shape(id);
71        let before_array = self.nodes.array_bytes();
72        install(&self.nodes, id, xmin, live);
73        self.index_add(id);
74        self.mark_node_dirty(id);
75        // ADR-0063: lazy string postings — just dirty-mark built pairs, and
76        // only after the version is installed (apply-before-dirty ordering).
77        self.string_dirty_mark_node(id);
78        self.charge(
79            charge as i64
80                + crate::memory::chain_growth(
81                    before_shape,
82                    self.node_chain_shape(id),
83                    node_version_stride(),
84                )
85                + self.nodes.array_bytes() as i64
86                - before_array as i64,
87        );
88        Ok(())
89    }
90
91    pub fn create_rel(
92        &self,
93        start: NodeId,
94        end: NodeId,
95        rel_type: String,
96        properties: BTreeMap<String, Value>,
97    ) -> Result<RelId> {
98        self.validate_rel_endpoints(start, end)?;
99        let id = self.alloc_rel_id()?;
100        self.install_rel(id, start, end, rel_type, properties)?;
101        Ok(id)
102    }
103
104    pub(in crate::graph) fn validate_rel_endpoints(
105        &self,
106        start: NodeId,
107        end: NodeId,
108    ) -> Result<()> {
109        checked_persisted_id(start, "relationship start")?;
110        checked_persisted_id(end, "relationship end")?;
111        // Endpoint existence without materializing the endpoint nodes.
112        let ts_now = self.read_ts();
113        if !self.node_visible_at(start, ts_now) || !self.node_visible_at(end, ts_now) {
114            return Err(super::missing_rel_endpoint_error());
115        }
116        Ok(())
117    }
118
119    pub(in crate::graph) fn install_rel(
120        &self,
121        id: RelId,
122        start: NodeId,
123        end: NodeId,
124        rel_type: String,
125        properties: BTreeMap<String, Value>,
126    ) -> Result<()> {
127        let next = checked_persisted_id(id, "relationship")?;
128        self.validate_rel_endpoints(start, end)?;
129        self.next_rel_id.fetch_max(next, Ordering::Relaxed);
130        self.catalog
131            .lock()
132            .unwrap()
133            .record_rel_type(rel_type.clone());
134        self.bump_stats(|s| {
135            s.relationships_created += 1;
136            s.properties_set += properties.len() as i64;
137        });
138        if self.recording() {
139            let op = RedoOp::create_rel(id, start, end, rel_type.clone(), properties.clone());
140            self.push_redo(op);
141        }
142        let xmin = self.xmin_for_install();
143        let live = LiveRel::from_parts(&self.interner, start, end, &rel_type, properties);
144        // ADR-0687: a create's report rule — its type id only, the
145        // property keys covered by the type stamp (`token_changes`'s
146        // "what a seam reports").
147        self.note_changed_tokens(std::iter::once(live.type_id));
148        let charge = crate::memory::live_rel_account_live(&live);
149        let ts = live.payload.ts(&self.interner);
150        let (out_side, in_side) = (self.out_side(), self.in_side());
151        let out_before = out_side.floor(start);
152        let in_before = in_side.floor(end);
153        let adj_arrays = out_side.delta().array_bytes() + in_side.delta().array_bytes();
154        let degree_before = self.out_chunk_len(start, live.type_id);
155        out_side.insert(start, live.type_id, id, ts);
156        in_side.insert(end, live.type_id, id, ts);
157        self.bump_degree_histograms(start, live.type_id, degree_before);
158        self.bump_rel_stats(start, live.type_id, end, CountDelta::Add);
159        let adj = out_side.floor(start) as i64 - out_before as i64 + in_side.floor(end) as i64
160            - in_before as i64
161            + (out_side.delta().array_bytes() + in_side.delta().array_bytes()) as i64
162            - adj_arrays as i64;
163        // ADR-0439: a created relationship introduces its constrained
164        // tuple(s); relationship constraints have no backing-index postings.
165        // The map's scope decides whether the relationship can change one.
166        // Its key ids resolve before the scope probe takes the map lock
167        // (interner shard read, then map lock — never the reverse).
168        let key_ids = live.payload.key_ids(&self.interner);
169        let edit = self.tracked_rel_edit(id, |scope| scope.touches_rel(live.type_id, &key_ids));
170        self.finish_rel_edit(edit, id, Some(&live));
171        let before_shape = self.rel_chain_shape(id);
172        let before_array = self.rels.array_bytes();
173        install(&self.rels, id, xmin, live);
174        self.mark_rel_dirty(id);
175        // ADR-0185: lazy relationship postings — dirty-mark built pairs, and
176        // only after the version is installed (apply-before-dirty ordering).
177        self.rel_index_add(id);
178        self.charge(
179            charge as i64
180                + crate::memory::chain_growth(
181                    before_shape,
182                    self.rel_chain_shape(id),
183                    rel_version_stride(),
184                )
185                + self.rels.array_bytes() as i64
186                - before_array as i64
187                + adj,
188        );
189        Ok(())
190    }
191
192    pub(in crate::graph) fn cow_node(&self, id: NodeId) -> Option<LiveNode> {
193        cow(&self.write_ts, &self.nodes, id)
194    }
195
196    pub(in crate::graph) fn put_node(&self, id: NodeId, live: LiveNode) {
197        // The write-back follows a successful `cow_node`, so the version
198        // chain exists by construction; a missing one is a broken invariant,
199        // never a silent discard of the edit.
200        *self
201            .nodes
202            .get_mut(&id)
203            .expect("put_node follows a successful cow_node")
204            .tail_live_mut() = live;
205    }
206
207    pub(in crate::graph) fn cow_rel(&self, id: RelId) -> Option<LiveRel> {
208        cow(&self.write_ts, &self.rels, id)
209    }
210
211    pub(in crate::graph) fn put_rel(&self, id: RelId, live: LiveRel) {
212        // The write-back follows a successful `cow_rel`, so the version chain
213        // exists by construction; a missing one is a broken invariant, never
214        // a silent discard of the edit.
215        *self
216            .rels
217            .get_mut(&id)
218            .expect("put_rel follows a successful cow_rel")
219            .tail_live_mut() = live;
220    }
221
222    pub fn set_property_node(&self, id: NodeId, key: &str, value: Value) {
223        let before = self.node(id);
224        if before.is_none() {
225            // No live entity: there is nothing to edit or to hand off.
226            return;
227        }
228        let before_shape = self.node_chain_shape(id);
229        // ADR-0439: capture the before-image only when a uniqueness
230        // constraint reads this key; a SET of an unconstrained property
231        // cannot change any tuple, so it skips the map entirely. The map's
232        // scope is the only source of that answer.
233        let keys = self.tracked_node_key_edit(id, key);
234        let mut n = self
235            .cow_node(id)
236            .expect("a live node has a copy-on-write version");
237        // ADR-0687's property-edit rule: report the key the edit touched
238        // beside the node's labels — the (label, key) equality and range
239        // cardinalities a seek consult read. A set interns its key; a removal
240        // resolves the id without minting and reports it only when the live
241        // version carried the key, so a `SET n.k = null` for a key the node
242        // never had changes nothing and stamps nothing.
243        let key_id = if value.is_null() {
244            self.interner
245                .get_id(key)
246                .filter(|&kid| n.props.get(kid).is_some())
247        } else {
248            Some(self.interner.intern(key))
249        };
250        self.note_changed_tokens(key_id.into_iter().chain(self.live_label_ids(id)));
251        let (op, props_set) = if value.is_null() {
252            if let Some(kid) = key_id {
253                n.props.remove(kid);
254            }
255            (RedoOp::remove_node_prop(id, key.to_string()), 0i64)
256        } else {
257            n.props
258                .set(key_id.expect("a set interns its key id"), value.clone());
259            (RedoOp::set_node_prop(id, key.to_string(), value.clone()), 1)
260        };
261        // The edited live view is in hand: hand it to the map before it
262        // moves into the version chain, never re-read it from the map.
263        self.finish_node_edit(keys, id, Some(&n));
264        self.put_node(id, n);
265        self.bump_stats(|s| s.properties_set += props_set);
266        self.push_redo(op);
267        self.mark_node_dirty(id);
268        // Dirty-mark only after the new version is installed — the ADR-0185
269        // invariant: `index_add` marks every (label, key) pair the installed
270        // version carries; a removal leaves stale postings, which the
271        // residual re-verification filters.
272        self.index_add(id);
273        self.charge_node_after_edit(id, before.as_ref(), before_shape);
274    }
275
276    pub fn set_property_rel(&self, id: RelId, key: &str, value: Value) {
277        if !self.rel_exists(id) {
278            // No live entity: there is nothing to edit or to hand off.
279            return;
280        }
281        let before_bytes = self.visible_rel_account(id);
282        let before_shape = self.rel_chain_shape(id);
283        let keys = self.tracked_rel_key_edit(id, key);
284        let mut r = self
285            .cow_rel(id)
286            .expect("a live relationship has a copy-on-write version");
287        let old_ts = r.payload.ts(&self.interner);
288        let start = r.start;
289        let end = r.end;
290        let type_id = r.type_id;
291        let xmax = self.tombstone_ts();
292        // ADR-0687's property-edit rule: the key the edit touched beside the
293        // rel type. A set interns its key; a removal resolves the id without
294        // minting and reports it only when the interner holds an id for a
295        // key the payload carried. A Triple payload answers its three
296        // structural field names (`id`, `amount`, `ts`) without the
297        // interner — `from_map` stores the shape and interns nothing — so
298        // removing one finds a carried value under a name with no id, and
299        // the id-keyed stamp table has nothing to record for it. The
300        // removal itself proceeds below either way.
301        let key_id = if value.is_null() {
302            match self.interner.get_id(key) {
303                Some(kid) => r.payload.get(&self.interner, key).is_some().then_some(kid),
304                None => None,
305            }
306        } else {
307            Some(self.interner.intern(key))
308        };
309        self.note_changed_tokens(key_id.into_iter().chain(std::iter::once(type_id)));
310        let (op, props_set) = if value.is_null() {
311            r.payload.remove(&self.interner, key);
312            (RedoOp::remove_rel_prop(id, key.to_string()), 0i64)
313        } else {
314            r.payload.set(&self.interner, key, value.clone());
315            (RedoOp::set_rel_prop(id, key.to_string(), value.clone()), 1)
316        };
317        let new_ts = r.payload.ts(&self.interner);
318        // The edited live view is in hand: hand it to the map before it
319        // moves into the version chain, never re-read it from the map.
320        self.finish_rel_edit(keys, id, Some(&r));
321        self.put_rel(id, r);
322        if old_ts != new_ts {
323            // A sealed position is superseded at `xmax` (ADR-0551); the
324            // new hop lands in the delta. The sealed charge is the event's
325            // price_side terms — the one formula the admission estimate
326            // prices batches with — never a whole-tier floor walk.
327            let (out_side, in_side) = (self.out_side(), self.in_side());
328            let adj_before = out_side.floor(start) + in_side.floor(end);
329            let (sealed_refusable, sealed_spill) =
330                self.price_sealed_event(start, end, type_id, id, Supersede::Repositioned);
331            out_side.reposition(start, type_id, id, new_ts, xmax);
332            in_side.reposition(end, type_id, id, new_ts, xmax);
333            self.charge(
334                (out_side.floor(start) + in_side.floor(end)) as i64 - adj_before as i64
335                    + sealed_refusable
336                    + sealed_spill,
337            );
338        }
339        // Dirty-mark only after the new version is installed — the
340        // ADR-0185 invariant: `rel_index_add` reads the installed version's
341        // own type and keys; a removal's key is gone from the payload, and
342        // its stale postings are filtered by the residual re-verification.
343        self.rel_index_add(id);
344        self.bump_stats(|s| s.properties_set += props_set);
345        self.push_redo(op);
346        self.mark_rel_dirty(id);
347        self.charge_rel_after_edit(id, before_bytes, before_shape);
348    }
349
350    /// Tombstone timestamp for a delete: the write ts while in a write,
351    /// else the commit ts clamped to ≥ 1 so the tombstone is never the
352    /// "no tombstone" sentinel 0. Both MVCC delete paths share this rule.
353    pub(in crate::graph) fn tombstone_ts(&self) -> u64 {
354        if self.in_write.load(Ordering::Acquire) {
355            self.write_ts.load(Ordering::Acquire)
356        } else {
357            self.commit_ts().max(1)
358        }
359    }
360
361    pub fn delete_rel(&self, id: RelId) {
362        let ts = self.tombstone_ts();
363        // ADR-0439: free the constrained tuple from the live version before
364        // the tombstone (entity guard first, map lock last).
365        self.constraint_keys_delete_rel(id);
366        let before_shape = self.rel_chain_shape(id);
367        let deleted = {
368            let Some(mut vers) = self.rels.get_mut(&id) else {
369                return;
370            };
371            let Some(live) = vers.tombstone(ts) else {
372                return;
373            };
374            let (start, end, type_id) = (live.start, live.end, live.type_id);
375            // ADR-0687's delete rule: the dying version's type and
376            // property-key ids while they still exist (`token_changes`'s
377            // "what a seam reports") — no later walk recovers them.
378            let mut changed = vec![type_id];
379            // The walk is the full set: the visitor never breaks, so its
380            // flow continues after every key id.
381            let walk = live.payload.key_ids(&self.interner).for_each(|kid| {
382                changed.push(kid);
383                ControlFlow::Continue(())
384            });
385            debug_assert!(walk.is_continue());
386            self.note_changed_tokens(changed);
387            // LABS-370: the pair counts are exact (the counting operator
388            // answers from them), so a delete leaves its (start-label, type,
389            // end-label) triples — the mirror of the create-path bump.
390            self.bump_rel_stats(start, type_id, end, CountDelta::Remove);
391            (start, end, type_id)
392        };
393        let (start, end, type_id) = deleted;
394        let (out_side, in_side) = (self.out_side(), self.in_side());
395        let adj_before = out_side.floor(start) + in_side.floor(end);
396        // The sealed charge is the event's price_side terms — the one
397        // formula the admission estimate prices batches with — priced
398        // before the tombstones land, never a whole-tier floor walk.
399        let (sealed_refusable, sealed_spill) =
400            self.price_sealed_event(start, end, type_id, id, Supersede::Deleted);
401        // ADR-0551: the hop keeps its slot with a versioned tombstone so an
402        // older snapshot still sees it — in the delta (visibility filters it)
403        // or in the sealed stream. Recording it unconditionally keeps the
404        // write path decode-free; the fold resolves a tombstone whose hop
405        // only ever lived in the delta.
406        out_side.tombstone_deleted(start, type_id, id, ts);
407        in_side.tombstone_deleted(end, type_id, id, ts);
408        let adj_after = out_side.floor(start) + in_side.floor(end);
409        self.charge(
410            crate::memory::chain_growth(
411                before_shape,
412                before_shape.after_delete(),
413                rel_version_stride(),
414            ) + adj_after as i64
415                - adj_before as i64
416                + sealed_refusable
417                + sealed_spill,
418        );
419        self.bump_stats(|s| s.relationships_deleted += 1);
420        self.push_redo(RedoOp::delete_rel(id));
421        self.mark_rel_dirty(id);
422    }
423
424    pub fn delete_node(&self, id: NodeId, detach: bool) -> Result<()> {
425        // The canonical incident scan: visibility-filtered at the read
426        // timestamp and self-loop-deduplicated (graph/adjacency.rs).
427        let incident = self.neighbors(id, relate_ir::Direction::Both);
428        if !detach && !incident.is_empty() {
429            return Err(delete_connected_node_error());
430        }
431        for rid in incident {
432            self.delete_rel(rid);
433        }
434        // ADR-0439: free the node's constrained tuple(s) from the live
435        // version before the tombstone (entity guard first, map lock last).
436        self.constraint_keys_delete_node(id);
437        let ts = self.tombstone_ts();
438        // The tombstone's dying labels, carried out of the `nodes` guard
439        // so the reclamation candidates (ADR-0595) are appended after it
440        // is released — the lock contract `suspect_postings` states, and
441        // the shape the label twins' sites already have. The one carrier of
442        // "the live version was tombstoned": a missing entry is a missing
443        // node, and every later step runs in one block off it.
444        // The one carrier of "the live version was tombstoned": its label
445        // ids and its property-key ids, both collected under the guard the
446        // dying version is borrowed in. A missing entry is a missing node,
447        // and every later step runs in one block off it.
448        let mut dying: Option<(Vec<u32>, Vec<u32>)> = None;
449        let before_shape = self.node_chain_shape(id);
450        if let Some(mut vers) = self.nodes.get_mut(&id) {
451            if let Some(live) = vers.tombstone(ts) {
452                // LABS-370 (v1 follow-up) / LABS-851: the exact label
453                // counts and the total node count follow every delete —
454                // the count state does not. The node-liveness seam's
455                // one call.
456                self.bump_node_population_stats(&live.labels, CountDelta::Remove);
457                let keys = live.props.iter().map(|(kid, _)| kid).collect();
458                dying = Some((live.labels.clone(), keys));
459            }
460        }
461        let Some((dying_labels, dying_keys)) = dying else {
462            return Ok(());
463        };
464        // ADR-0687's delete rule: the dying version's label ids AND its
465        // property-key ids — the tombstone is the last place the keys
466        // exist, so no later walk could report them (`token_changes`'
467        // "what a seam reports"; `delete_rel`'s report is the twin).
468        self.note_changed_tokens(dying_labels.iter().copied().chain(dying_keys));
469        // ADR-0595: the tombstone's dying buckets — the labels the
470        // record carried, or the empty-label bucket when it carried
471        // none — become reclamation candidates here, at the removal
472        // site, for the apply's tail drain.
473        self.suspect_postings(id, &dying_labels);
474        self.charge(crate::memory::chain_growth(
475            before_shape,
476            before_shape.after_delete(),
477            node_version_stride(),
478        ));
479        self.bump_stats(|s| s.nodes_deleted += 1);
480        self.push_redo(RedoOp::delete_node(id));
481        self.mark_node_dirty(id);
482        Ok(())
483    }
484}
485
486/// Install `live` as `id`'s newest version: a fresh id gets an inline slot;
487/// an id that already has versions (a replayed re-create) keeps them.
488fn install<Live>(map: &IdVec<Chain<Live>>, id: i64, xmin: u64, live: Live) {
489    match map.entry(id) {
490        super::id_vec::Entry::Occupied(mut slot) => slot.get_mut().push(Ver {
491            xmin,
492            xmax: 0,
493            live,
494        }),
495        super::id_vec::Entry::Vacant(mut slot) => {
496            slot.insert(Chain::inline(xmin, live));
497        }
498    }
499}