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 super::adjacency::adj_tombstone_deleted;
10use super::id_vec::IdVec;
11use super::*;
12
13impl Graph {
14    pub fn create_node(
15        &self,
16        labels: Vec<String>,
17        properties: BTreeMap<String, Value>,
18    ) -> Result<NodeId> {
19        let id = self.alloc_node_id()?;
20        self.install_node(id, labels, properties)?;
21        Ok(id)
22    }
23
24    pub(in crate::graph) fn install_node(
25        &self,
26        id: NodeId,
27        labels: Vec<String>,
28        properties: BTreeMap<String, Value>,
29    ) -> Result<()> {
30        let next = checked_persisted_id(id, "node")?;
31        self.next_node_id.fetch_max(next, Ordering::Relaxed);
32        self.catalog
33            .lock()
34            .unwrap()
35            .record_labels(labels.iter().cloned());
36        self.bump_stats(|s| {
37            s.nodes_created += 1;
38            s.labels_added += labels.len() as i64;
39            s.properties_set += properties.len() as i64;
40        });
41        if self.recording() {
42            self.push_redo(RedoOp::create_node(
43                id,
44                std::sync::Arc::new(labels.clone()),
45                properties.clone(),
46            ));
47        }
48        let xmin = self.xmin_for_install();
49        let live = LiveNode::from_parts(&self.interner, labels, properties);
50        let charge =
51            crate::memory::live_node_account_live(&live, &self.interner, &self.index_charge());
52        // LABS-370 (v1 follow-up) / LABS-851: the exact label counts
53        // and the total node count follow every create, before the
54        // version owns the live set — the node-liveness seam's one
55        // call.
56        self.bump_node_population_stats(&live.labels, CountDelta::Add);
57        // ADR-0439: a created node introduces its constrained tuple(s); a
58        // replay that re-creates an id frees the previous live tuple first.
59        // The map's scope decides whether the node can change any tuple.
60        let edit = self.tracked_node_edit(id, |scope| {
61            scope.touches_node(&live.labels, live.props.iter().map(|(kid, _)| kid))
62        });
63        self.finish_node_edit(edit, id, Some(&live));
64        let before_shape = self.node_chain_shape(id);
65        let before_array = self.nodes.array_bytes();
66        install(&self.nodes, id, xmin, live);
67        self.index_add(id);
68        self.mark_node_dirty(id);
69        // ADR-0063: lazy string postings — just dirty-mark built pairs, and
70        // only after the version is installed (apply-before-dirty ordering).
71        self.string_dirty_mark_node(id);
72        self.charge(
73            charge as i64 + crate::memory::node_chain_bytes(self.node_chain_shape(id)) as i64
74                - crate::memory::node_chain_bytes(before_shape) as i64
75                + self.nodes.array_bytes() as i64
76                - before_array as i64,
77        );
78        Ok(())
79    }
80
81    pub fn create_rel(
82        &self,
83        start: NodeId,
84        end: NodeId,
85        rel_type: String,
86        properties: BTreeMap<String, Value>,
87    ) -> Result<RelId> {
88        self.validate_rel_endpoints(start, end)?;
89        let id = self.alloc_rel_id()?;
90        self.install_rel(id, start, end, rel_type, properties)?;
91        Ok(id)
92    }
93
94    pub(in crate::graph) fn validate_rel_endpoints(
95        &self,
96        start: NodeId,
97        end: NodeId,
98    ) -> Result<()> {
99        checked_persisted_id(start, "relationship start")?;
100        checked_persisted_id(end, "relationship end")?;
101        // Endpoint existence without materializing the endpoint nodes.
102        let ts_now = self.read_ts();
103        if !self.node_visible_at(start, ts_now) || !self.node_visible_at(end, ts_now) {
104            return Err(super::missing_rel_endpoint_error());
105        }
106        Ok(())
107    }
108
109    pub(in crate::graph) fn install_rel(
110        &self,
111        id: RelId,
112        start: NodeId,
113        end: NodeId,
114        rel_type: String,
115        properties: BTreeMap<String, Value>,
116    ) -> Result<()> {
117        let next = checked_persisted_id(id, "relationship")?;
118        self.validate_rel_endpoints(start, end)?;
119        self.next_rel_id.fetch_max(next, Ordering::Relaxed);
120        self.catalog
121            .lock()
122            .unwrap()
123            .record_rel_type(rel_type.clone());
124        self.bump_stats(|s| {
125            s.relationships_created += 1;
126            s.properties_set += properties.len() as i64;
127        });
128        if self.recording() {
129            let op = RedoOp::create_rel(id, start, end, rel_type.clone(), properties.clone());
130            self.push_redo(op);
131        }
132        let xmin = self.xmin_for_install();
133        let live = LiveRel::from_parts(&self.interner, start, end, &rel_type, properties);
134        let charge = crate::memory::live_rel_account_live(&live);
135        let ts = live.payload.ts(&self.interner);
136        let out_before = adj_floor(&self.out_adj, &self.sealed_out, start);
137        let in_before = adj_floor(&self.in_adj, &self.sealed_in, end);
138        let adj_arrays = self.out_adj.array_bytes() + self.in_adj.array_bytes();
139        let degree_before = self.out_chunk_len(start, live.type_id);
140        adj_insert(&self.out_adj, start, live.type_id, id, ts);
141        adj_insert(&self.in_adj, end, live.type_id, id, ts);
142        self.bump_degree_histograms(start, live.type_id, degree_before);
143        self.bump_rel_stats(start, live.type_id, end, CountDelta::Add);
144        let adj = adj_floor(&self.out_adj, &self.sealed_out, start) as i64 - out_before as i64
145            + adj_floor(&self.in_adj, &self.sealed_in, end) as i64
146            - in_before as i64
147            + (self.out_adj.array_bytes() + self.in_adj.array_bytes()) as i64
148            - adj_arrays as i64;
149        // ADR-0439: a created relationship introduces its constrained
150        // tuple(s); relationship constraints have no backing-index postings.
151        // The map's scope decides whether the relationship can change one.
152        // Its key ids resolve before the scope probe takes the map lock
153        // (interner shard read, then map lock — never the reverse).
154        let key_ids = live.payload.key_ids(&self.interner);
155        let edit = self.tracked_rel_edit(id, |scope| scope.touches_rel(live.type_id, &key_ids));
156        self.finish_rel_edit(edit, id, Some(&live));
157        let before_shape = self.rel_chain_shape(id);
158        let before_array = self.rels.array_bytes();
159        install(&self.rels, id, xmin, live);
160        self.mark_rel_dirty(id);
161        // ADR-0185: lazy relationship postings — dirty-mark built pairs, and
162        // only after the version is installed (apply-before-dirty ordering).
163        self.rel_index_add(id);
164        self.charge(
165            charge as i64 + crate::memory::rel_chain_bytes(self.rel_chain_shape(id)) as i64
166                - crate::memory::rel_chain_bytes(before_shape) as i64
167                + self.rels.array_bytes() as i64
168                - before_array as i64
169                + adj,
170        );
171        Ok(())
172    }
173
174    pub(in crate::graph) fn cow_node(&self, id: NodeId) -> Option<LiveNode> {
175        cow(&self.write_ts, &self.nodes, id)
176    }
177
178    pub(in crate::graph) fn put_node(&self, id: NodeId, live: LiveNode) {
179        // The write-back follows a successful `cow_node`, so the version
180        // chain exists by construction; a missing one is a broken invariant,
181        // never a silent discard of the edit.
182        *self
183            .nodes
184            .get_mut(&id)
185            .expect("put_node follows a successful cow_node")
186            .tail_live_mut() = live;
187    }
188
189    pub(in crate::graph) fn cow_rel(&self, id: RelId) -> Option<LiveRel> {
190        cow(&self.write_ts, &self.rels, id)
191    }
192
193    pub(in crate::graph) fn put_rel(&self, id: RelId, live: LiveRel) {
194        // The write-back follows a successful `cow_rel`, so the version chain
195        // exists by construction; a missing one is a broken invariant, never
196        // a silent discard of the edit.
197        *self
198            .rels
199            .get_mut(&id)
200            .expect("put_rel follows a successful cow_rel")
201            .tail_live_mut() = live;
202    }
203
204    pub fn set_property_node(&self, id: NodeId, key: &str, value: Value) {
205        let before = self.node(id);
206        if before.is_none() {
207            // No live entity: there is nothing to edit or to hand off.
208            return;
209        }
210        let before_shape = self.node_chain_shape(id);
211        // ADR-0439: capture the before-image only when a uniqueness
212        // constraint reads this key; a SET of an unconstrained property
213        // cannot change any tuple, so it skips the map entirely. The map's
214        // scope is the only source of that answer.
215        let keys = self.tracked_node_key_edit(id, key);
216        let mut n = self
217            .cow_node(id)
218            .expect("a live node has a copy-on-write version");
219        let kid = self.interner.intern(key);
220        let (op, props_set) = if value.is_null() {
221            n.props.remove(kid);
222            (RedoOp::remove_node_prop(id, key.to_string()), 0i64)
223        } else {
224            n.props.set(kid, value.clone());
225            (RedoOp::set_node_prop(id, key.to_string(), value.clone()), 1)
226        };
227        // The edited live view is in hand: hand it to the map before it
228        // moves into the version chain, never re-read it from the map.
229        self.finish_node_edit(keys, id, Some(&n));
230        self.put_node(id, n);
231        self.bump_stats(|s| s.properties_set += props_set);
232        self.push_redo(op);
233        self.mark_node_dirty(id);
234        // Dirty-mark only after the new version is installed — the ADR-0185
235        // invariant: `index_add` marks every (label, key) pair the installed
236        // version carries; a removal leaves stale postings, which the
237        // residual re-verification filters.
238        self.index_add(id);
239        self.charge_node_after_edit(id, before.as_ref(), before_shape);
240    }
241
242    pub fn set_property_rel(&self, id: RelId, key: &str, value: Value) {
243        if !self.rel_exists(id) {
244            // No live entity: there is nothing to edit or to hand off.
245            return;
246        }
247        let before_bytes = self.visible_rel_account(id);
248        let before_shape = self.rel_chain_shape(id);
249        let keys = self.tracked_rel_key_edit(id, key);
250        let mut r = self
251            .cow_rel(id)
252            .expect("a live relationship has a copy-on-write version");
253        let old_ts = r.payload.ts(&self.interner);
254        let start = r.start;
255        let end = r.end;
256        let type_id = r.type_id;
257        let xmax = self.tombstone_ts();
258        let (op, props_set) = if value.is_null() {
259            r.payload.remove(&self.interner, key);
260            (RedoOp::remove_rel_prop(id, key.to_string()), 0i64)
261        } else {
262            r.payload.set(&self.interner, key, value.clone());
263            (RedoOp::set_rel_prop(id, key.to_string(), value.clone()), 1)
264        };
265        let new_ts = r.payload.ts(&self.interner);
266        // The edited live view is in hand: hand it to the map before it
267        // moves into the version chain, never re-read it from the map.
268        self.finish_rel_edit(keys, id, Some(&r));
269        self.put_rel(id, r);
270        if old_ts != new_ts {
271            // A sealed position is superseded at `xmax` (ADR-0551); the
272            // new hop lands in the delta.
273            let adj_before = adj_floor(&self.out_adj, &self.sealed_out, start)
274                + adj_floor(&self.in_adj, &self.sealed_in, end);
275            adj_reposition(
276                &self.out_adj,
277                &self.sealed_out,
278                start,
279                type_id,
280                id,
281                new_ts,
282                xmax,
283            );
284            adj_reposition(
285                &self.in_adj,
286                &self.sealed_in,
287                end,
288                type_id,
289                id,
290                new_ts,
291                xmax,
292            );
293            self.charge(
294                (adj_floor(&self.out_adj, &self.sealed_out, start)
295                    + adj_floor(&self.in_adj, &self.sealed_in, end)) as i64
296                    - adj_before as i64,
297            );
298        }
299        // Dirty-mark only after the new version is installed — the
300        // ADR-0185 invariant: `rel_index_add` reads the installed version's
301        // own type and keys; a removal's key is gone from the payload, and
302        // its stale postings are filtered by the residual re-verification.
303        self.rel_index_add(id);
304        self.bump_stats(|s| s.properties_set += props_set);
305        self.push_redo(op);
306        self.mark_rel_dirty(id);
307        self.charge_rel_after_edit(id, before_bytes, before_shape);
308    }
309
310    pub fn merge_properties_node(&self, id: NodeId, map: &BTreeMap<String, Value>) {
311        // One cycle for the whole map, mirroring how `install_node` takes a
312        // map in one pass: one scope probe, one cow, one tracked-edit
313        // completion, one index/charge update.
314        let before = self.node(id);
315        if before.is_none() || map.is_empty() {
316            return;
317        }
318        let before_shape = self.node_chain_shape(id);
319        let keys = self.tracked_node_edit(id, |scope| {
320            map.keys().any(|key| {
321                self.interner
322                    .get_id(key)
323                    .is_some_and(|kid| scope.touches_node_key(kid))
324            })
325        });
326        let mut n = self
327            .cow_node(id)
328            .expect("a live node has a copy-on-write version");
329        let mut props_set = 0i64;
330        let mut ops = Vec::with_capacity(map.len());
331        for (key, value) in map {
332            let kid = self.interner.intern(key);
333            if value.is_null() {
334                n.props.remove(kid);
335                ops.push(RedoOp::remove_node_prop(id, key.clone()));
336            } else {
337                n.props.set(kid, value.clone());
338                props_set += 1;
339                ops.push(RedoOp::set_node_prop(id, key.clone(), value.clone()));
340            }
341        }
342        // The edited live view is in hand: hand it to the map before it
343        // moves into the version chain.
344        self.finish_node_edit(keys, id, Some(&n));
345        self.put_node(id, n);
346        self.bump_stats(|s| s.properties_set += props_set);
347        for op in ops {
348            self.push_redo(op);
349        }
350        self.mark_node_dirty(id);
351        self.index_add(id);
352        self.charge_node_after_edit(id, before.as_ref(), before_shape);
353    }
354
355    /// Tombstone timestamp for a delete: the write ts while in a write,
356    /// else the commit ts clamped to ≥ 1 so the tombstone is never the
357    /// "no tombstone" sentinel 0. Both MVCC delete paths share this rule.
358    pub(in crate::graph) fn tombstone_ts(&self) -> u64 {
359        if self.in_write.load(Ordering::Acquire) {
360            self.write_ts.load(Ordering::Acquire)
361        } else {
362            self.commit_ts().max(1)
363        }
364    }
365
366    pub fn delete_rel(&self, id: RelId) {
367        let ts = self.tombstone_ts();
368        // ADR-0439: free the constrained tuple from the live version before
369        // the tombstone (entity guard first, map lock last).
370        self.constraint_keys_delete_rel(id);
371        let before_shape = self.rel_chain_shape(id);
372        let deleted = {
373            let Some(mut vers) = self.rels.get_mut(&id) else {
374                return;
375            };
376            let Some(live) = vers.tombstone(ts) else {
377                return;
378            };
379            let (start, end, type_id) = (live.start, live.end, live.type_id);
380            // LABS-370: the pair counts are exact (the counting operator
381            // answers from them), so a delete leaves its (start-label, type,
382            // end-label) triples — the mirror of the create-path bump.
383            self.bump_rel_stats(start, type_id, end, CountDelta::Remove);
384            (start, end, type_id)
385        };
386        let (start, end, type_id) = deleted;
387        let adj_before = adj_floor(&self.out_adj, &self.sealed_out, start)
388            + adj_floor(&self.in_adj, &self.sealed_in, end);
389        let sealed_arrays_before = self.sealed_out.array_bytes() + self.sealed_in.array_bytes();
390        // ADR-0551: the hop keeps its slot with a versioned tombstone so an
391        // older snapshot still sees it — in the delta (visibility filters it)
392        // or in the sealed stream. Recording it unconditionally keeps the
393        // write path decode-free; the fold resolves a tombstone whose hop
394        // only ever lived in the delta.
395        adj_tombstone_deleted(&self.sealed_out, start, type_id, id, ts);
396        adj_tombstone_deleted(&self.sealed_in, end, type_id, id, ts);
397        let adj_after = adj_floor(&self.out_adj, &self.sealed_out, start)
398            + adj_floor(&self.in_adj, &self.sealed_in, end);
399        self.charge(
400            crate::memory::rel_chain_bytes(before_shape.after_delete()) as i64
401                - crate::memory::rel_chain_bytes(before_shape) as i64
402                + adj_after as i64
403                - adj_before as i64
404                + (self.sealed_out.array_bytes() + self.sealed_in.array_bytes()) as i64
405                - sealed_arrays_before as i64,
406        );
407        self.bump_stats(|s| s.relationships_deleted += 1);
408        self.push_redo(RedoOp::delete_rel(id));
409        self.mark_rel_dirty(id);
410    }
411
412    pub fn delete_node(&self, id: NodeId, detach: bool) -> Result<()> {
413        // The canonical incident scan: visibility-filtered at the read
414        // timestamp and self-loop-deduplicated (graph/adjacency.rs).
415        let incident = self.neighbors(id, relate_ir::Direction::Both);
416        if !detach && !incident.is_empty() {
417            return Err(delete_connected_node_error());
418        }
419        for rid in incident {
420            self.delete_rel(rid);
421        }
422        // ADR-0439: free the node's constrained tuple(s) from the live
423        // version before the tombstone (entity guard first, map lock last).
424        self.constraint_keys_delete_node(id);
425        let ts = self.tombstone_ts();
426        let mut found = false;
427        let before_shape = self.node_chain_shape(id);
428        if let Some(mut vers) = self.nodes.get_mut(&id) {
429            if let Some(live) = vers.tombstone(ts) {
430                // LABS-370 (v1 follow-up) / LABS-851: the exact label
431                // counts and the total node count follow every delete —
432                // the label index keeps the tombstoned id until GC, the
433                // count state does not. The node-liveness seam's one
434                // call.
435                self.bump_node_population_stats(&live.labels, CountDelta::Remove);
436                found = true;
437            }
438        }
439        if found {
440            self.charge(
441                crate::memory::node_chain_bytes(before_shape.after_delete()) as i64
442                    - crate::memory::node_chain_bytes(before_shape) as i64,
443            );
444            self.bump_stats(|s| s.nodes_deleted += 1);
445            self.push_redo(RedoOp::delete_node(id));
446            self.mark_node_dirty(id);
447        }
448        Ok(())
449    }
450}
451
452/// Install `live` as `id`'s newest version: a fresh id gets an inline slot;
453/// an id that already has versions (a replayed re-create) keeps them.
454fn install<Live>(map: &IdVec<Chain<Live>>, id: i64, xmin: u64, live: Live) {
455    match map.entry(id) {
456        super::id_vec::Entry::Occupied(mut slot) => slot.get_mut().push(Ver {
457            xmin,
458            xmax: 0,
459            live,
460        }),
461        super::id_vec::Entry::Vacant(mut slot) => {
462            slot.insert(Chain::inline(xmin, live));
463        }
464    }
465}