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