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