Skip to main content

relate_executor/overlay/
writes.rs

1//! The write verbs: every overlay mutation (`create_node`, `create_rel`,
2//! `add_labels`/`remove_labels`, the `set_property_*` /
3//! `merge_properties_*` / `replace_properties_*` family, `delete_*`)
4//! funnels through [`WriteScratch::push_redo`], so the redo log and the
5//! lazy equality indexes stay current for every write. Stats accounting
6//! (creates, deletes, properties set/removed, net label deltas) happens
7//! here, next to the mutation it counts: the openCypher graph-diff
8//! counters (net new label names, property set/removed pairs) and Neo4j's
9//! update counters beside them (labels per node, one property write per
10//! write, ADR-0309).
11
12use std::collections::{BTreeMap, HashSet};
13
14use relate_core::{Node, NodeId, RelId, Relationship, Result, Value};
15use relate_ir::Direction;
16
17use crate::graph::Graph;
18use crate::redo::RedoOp;
19
20use super::label_probe::LabelChange;
21use super::{distinct_labels, ExecGraph, WriteScratch};
22
23impl ExecGraph<'_> {
24    pub fn create_node(
25        &self,
26        labels: Vec<String>,
27        properties: BTreeMap<String, Value>,
28    ) -> Result<NodeId> {
29        let mut s = self.scratch_mut();
30        let labels = std::sync::Arc::new(labels);
31        let properties = std::sync::Arc::new(relate_core::PropertyMap::from(properties));
32        let (labels_added, labels_removed) = self.label_deltas(&s, &labels, LabelChange::Gain);
33        s.reserve_new_node(&Node {
34            id: 0,
35            labels: std::sync::Arc::clone(&labels),
36            properties: std::sync::Arc::clone(&properties),
37        })?;
38        let id = s.alloc_node()?;
39        s.statement.stats.nodes_created += 1;
40        s.net_label_stats(labels_added, labels_removed);
41        s.statement.stats.properties_set += properties.len() as i64;
42        s.batch.nodes.insert(
43            id,
44            Node {
45                id,
46                labels: std::sync::Arc::clone(&labels),
47                properties: std::sync::Arc::clone(&properties),
48            },
49        );
50        s.bump_live_labels(&labels, 1);
51        s.batch.created_nodes.insert(id);
52        s.push_redo(RedoOp::CreateNode {
53            id,
54            labels,
55            properties,
56        });
57        drop(s);
58        relate_core::tokens::poll()?;
59        Ok(id)
60    }
61
62    pub fn create_rel(
63        &self,
64        start: NodeId,
65        end: NodeId,
66        rel_type: String,
67        properties: BTreeMap<String, Value>,
68    ) -> Result<RelId> {
69        if !self.node_exists(start) || !self.node_exists(end) {
70            return Err(crate::graph::missing_rel_endpoint_error());
71        }
72        let properties = std::sync::Arc::new(relate_core::PropertyMap::from(properties));
73        let mut s = self.scratch_mut();
74        s.reserve_new_rel(&Relationship {
75            id: 0,
76            start,
77            end,
78            rel_type: rel_type.clone(),
79            properties: std::sync::Arc::clone(&properties),
80        })?;
81        let id = s.alloc_rel()?;
82        s.statement.stats.relationships_created += 1;
83        s.statement.stats.properties_set += properties.len() as i64;
84        s.batch.rels.insert(
85            id,
86            Relationship {
87                id,
88                start,
89                end,
90                rel_type: rel_type.clone(),
91                properties: std::sync::Arc::clone(&properties),
92            },
93        );
94        s.batch.out_adj.entry(start).or_default().push(id);
95        s.batch.in_adj.entry(end).or_default().push(id);
96        s.batch.created_rels.insert(id);
97        s.push_redo(RedoOp::CreateRel {
98            id,
99            start,
100            end,
101            rel_type,
102            properties,
103        });
104        drop(s);
105        relate_core::tokens::poll()?;
106        Ok(id)
107    }
108
109    fn cow_node<'b>(s: &'b mut WriteScratch, base: &Graph, id: NodeId) -> Option<&'b mut Node> {
110        if s.batch.deleted_nodes.contains(&id) {
111            return None;
112        }
113        if !s.batch.nodes.contains_key(&id) {
114            let n = base.node_at(id, s.snapshot_ts())?;
115            // LABS-1085 review: a copy-on-write introduces the base node
116            // into the scratch, so its whole label/property vocabulary
117            // posts into the equality index — exactly what a create
118            // posts. Without this, a pair built before the cow misses
119            // the node's pre-existing properties, and a keyed lookup
120            // (MERGE's match arm) silently misses the node and creates
121            // a duplicate. Set/label ops on the copy post on top;
122            // postings are sets, so a double post is harmless.
123            for (key, value) in &*n.properties {
124                s.batch.prop_ix.post_value(id, &n.labels, key, value);
125            }
126            s.batch.nodes.insert(id, n);
127        }
128        s.batch.nodes.get_mut(&id)
129    }
130
131    fn cow_rel<'b>(
132        s: &'b mut WriteScratch,
133        base: &Graph,
134        id: RelId,
135    ) -> Option<&'b mut Relationship> {
136        if s.batch.deleted_rels.contains(&id) {
137            return None;
138        }
139        if !s.batch.rels.contains_key(&id) {
140            let r = base.rel_at(id, s.snapshot_ts())?;
141            // The node cow's posting contract (above), on the rel index.
142            for (key, value) in &*r.properties {
143                s.batch.rel_prop_ix.post_value(id, &r.rel_type, key, value);
144            }
145            s.batch.rels.insert(id, r);
146        }
147        s.batch.rels.get_mut(&id)
148    }
149
150    pub fn add_labels(&self, id: NodeId, labels: &[String]) {
151        if labels.is_empty() {
152            return;
153        }
154        let existing = self.node_labels(id).unwrap_or_default();
155        // The labels this write actually adds: the distinct requested labels
156        // not already on the node, in first-occurrence order. Computed once
157        // and reused for the accounting and the cow block; `n.labels ==
158        // existing` at cow time, so the cow block pushes `fresh` as-is
159        // instead of re-answering the membership question per label.
160        let fresh: Vec<String> = distinct_labels(labels)
161            .into_iter()
162            .filter(|l| !existing.iter().any(|x| x == *l))
163            .map(str::to_string)
164            .collect();
165        let mut s = self.scratch_mut();
166        let (labels_added, labels_removed) = self.label_deltas(&s, &fresh, LabelChange::Gain);
167        let before_labels = created_label_snapshot(&s, id);
168        let mut added = Vec::new();
169        if let Some(n) = Self::cow_node(&mut s, self.base, id) {
170            std::sync::Arc::make_mut(&mut n.labels).extend(fresh.iter().cloned());
171            added = fresh;
172        }
173        shift_created_labels(&mut s, id, before_labels);
174        s.net_label_stats(labels_added, labels_removed);
175        if !added.is_empty() {
176            s.bump_live_labels(&added, 1);
177            s.push_redo(RedoOp::add_labels(id, added));
178        }
179    }
180
181    pub fn remove_labels(&self, id: NodeId, labels: &[String]) {
182        // Cow the node first and derive everything from `n.labels` in one
183        // pass: `extract_if` walks the node's labels once, dropping the
184        // ones the request names and collecting them into `actually` in
185        // node order. `requested` answers membership in O(1) per node
186        // label; `actually` feeds the accounting and the live-label bump
187        // (both consumers dedupe, so node order is as good as request
188        // order). A missing or scratch-deleted node leaves `actually`
189        // empty, exactly what the pre-cow read answered for it.
190        let requested: HashSet<&str> = labels.iter().map(String::as_str).collect();
191        let mut s = self.scratch_mut();
192        let before_labels = created_label_snapshot(&s, id);
193        let mut actually: Vec<String> = Vec::new();
194        if let Some(n) = Self::cow_node(&mut s, self.base, id) {
195            actually = std::sync::Arc::make_mut(&mut n.labels)
196                .extract_if(.., |l| requested.contains(l.as_str()))
197                .collect();
198        }
199        shift_created_labels(&mut s, id, before_labels);
200        let (labels_added, labels_removed) = self.label_deltas(&s, &actually, LabelChange::Loss);
201        s.net_label_stats(labels_added, labels_removed);
202        if !actually.is_empty() {
203            s.bump_live_labels(&actually, -1);
204            // The op carries the labels the node actually lost, so the
205            // ADR-0309 per-node count is derived from it (a requested label
206            // the node did not carry is a no-op).
207            s.push_redo(RedoOp::remove_labels(id, actually));
208        }
209    }
210
211    /// CIP-162 overwrite semantics, spelled once beside the primitives it
212    /// composes: the node's labels become exactly `labels` — the ones it
213    /// carries but the list omits leave ([`remove_labels`]), then the
214    /// list's labels arrive ([`add_labels`]). Each half keeps its own
215    /// accounting and redo, so the overwrite is their compose, not a third
216    /// label-write path.
217    pub fn set_labels(&self, id: NodeId, labels: &[String]) {
218        let current = self.node_labels(id).unwrap_or_default();
219        let remove: Vec<String> = current
220            .into_iter()
221            .filter(|label| !labels.contains(label))
222            .collect();
223        // An empty diff skips the remove half (mirroring add_labels' own
224        // empty-list guard) instead of cowing the node for nothing.
225        if !remove.is_empty() {
226            self.remove_labels(id, &remove);
227        }
228        self.add_labels(id, labels);
229    }
230
231    pub fn set_property_node(&self, id: NodeId, key: &str, value: Value) {
232        let mut s = self.scratch_mut();
233        let created = s.batch.created_nodes.contains(&id);
234        let before_props = created_property_snapshot(&s, id, created);
235        let outcome = Self::cow_node(&mut s, self.base, id).map(|n| {
236            set_prop_core(
237                std::sync::Arc::make_mut(&mut n.properties),
238                created,
239                key,
240                &value,
241            )
242        });
243        shift_created_properties(&mut s, id, before_props);
244        let ((set, removed), op) = outcome.unwrap_or(((0, 0), None));
245        s.statement.stats.properties_set += set;
246        s.statement.stats.properties_removed += removed;
247        if let Some(op) = op {
248            s.push_redo(match op {
249                PropOpKind::Set(k, v) => RedoOp::set_node_prop(id, k, v),
250                PropOpKind::Remove(k) => RedoOp::remove_node_prop(id, k),
251            });
252        }
253    }
254
255    pub fn set_property_rel(&self, id: RelId, key: &str, value: Value) {
256        let mut s = self.scratch_mut();
257        let created = s.batch.created_rels.contains(&id);
258        let before_props = created_rel_property_snapshot(&s, id, created);
259        let outcome = Self::cow_rel(&mut s, self.base, id).map(|r| {
260            set_prop_core(
261                std::sync::Arc::make_mut(&mut r.properties),
262                created,
263                key,
264                &value,
265            )
266        });
267        shift_created_rel_properties(&mut s, id, before_props);
268        let ((set, removed), op) = outcome.unwrap_or(((0, 0), None));
269        s.statement.stats.properties_set += set;
270        s.statement.stats.properties_removed += removed;
271        if let Some(op) = op {
272            s.push_redo(match op {
273                PropOpKind::Set(k, v) => RedoOp::set_rel_prop(id, k, v),
274                PropOpKind::Remove(k) => RedoOp::remove_rel_prop(id, k),
275            });
276        }
277    }
278
279    /// `SET n += map`: per-key merge through the set verb (an existing
280    /// key keeps its position, a new one is added) — the node and
281    /// relationship forms are the same loop over their set verbs.
282    pub fn merge_properties_node(&self, id: NodeId, map: &BTreeMap<String, Value>) {
283        for (k, v) in map {
284            self.set_property_node(id, k, v.clone());
285        }
286    }
287
288    /// The relationship form of [`Self::merge_properties_node`].
289    pub fn merge_properties_rel(&self, id: RelId, map: &BTreeMap<String, Value>) {
290        for (k, v) in map {
291            self.set_property_rel(id, k, v.clone());
292        }
293    }
294
295    pub fn replace_properties_node(&self, id: NodeId, map: BTreeMap<String, Value>) {
296        let keys: Vec<String> = self
297            .node(id)
298            .map(|n| n.properties.keys().cloned().collect())
299            .unwrap_or_default();
300        replace_props(keys, map, |k, v| self.set_property_node(id, k, v));
301    }
302
303    pub fn replace_properties_rel(&self, id: RelId, map: BTreeMap<String, Value>) {
304        let keys: Vec<String> = self
305            .rel(id)
306            .map(|r| r.properties.keys().cloned().collect())
307            .unwrap_or_default();
308        replace_props(keys, map, |k, v| self.set_property_rel(id, k, v));
309    }
310
311    pub fn delete_rel(&self, id: RelId) {
312        let nprops = match self.rel(id) {
313            Some(r) => r.properties.len() as i64,
314            None => return,
315        };
316        let mut s = self.scratch_mut();
317        let removed = created_rel_removal(&s, id);
318        s.batch.deleted_rels.insert(id);
319        s.batch.rels.remove(&id);
320        if s.batch.created_rels.remove(&id) {
321            if let Some(delta) = removed {
322                s.shift_workspace(delta, 0);
323            }
324            s.statement.stats.relationships_created =
325                s.statement.stats.relationships_created.saturating_sub(1);
326            s.statement.stats.properties_set =
327                s.statement.stats.properties_set.saturating_sub(nprops);
328        } else {
329            s.statement.stats.relationships_deleted += 1;
330            s.statement.stats.properties_removed += nprops;
331        }
332        s.push_redo(RedoOp::delete_rel(id));
333    }
334
335    pub fn delete_node(&self, id: NodeId, detach: bool) -> Result<()> {
336        let incident: Vec<RelId> = self.neighbors(id, Direction::Both);
337        if !detach && !incident.is_empty() {
338            return Err(crate::graph::delete_connected_node_error());
339        }
340        for rid in &incident {
341            self.delete_rel(*rid);
342        }
343        // One fetch answers both "is the node live" and "what does it
344        // carry": a missing node has nothing to delete.
345        let Some(node) = self.node(id) else {
346            return Ok(());
347        };
348        let nprops = node.properties.len() as i64;
349        let labels = node.labels;
350        let mut s = self.scratch_mut();
351        let (labels_added, labels_removed) = self.label_deltas(&s, &labels, LabelChange::Loss);
352        let removed = created_node_removal(&s, id);
353        s.batch.deleted_nodes.insert(id);
354        s.batch.nodes.remove(&id);
355        s.bump_live_labels(&labels, -1);
356        s.net_label_stats(labels_added, labels_removed);
357        if s.batch.created_nodes.remove(&id) {
358            if let Some(delta) = removed {
359                s.shift_workspace(delta, 0);
360            }
361            s.statement.stats.nodes_created = s.statement.stats.nodes_created.saturating_sub(1);
362            s.statement.stats.properties_set =
363                s.statement.stats.properties_set.saturating_sub(nprops);
364        } else {
365            s.statement.stats.nodes_deleted += 1;
366            s.statement.stats.properties_removed += nprops;
367        }
368        s.push_redo(RedoOp::delete_node(id));
369        Ok(())
370    }
371}
372
373fn created_label_snapshot(s: &WriteScratch, id: NodeId) -> Option<u64> {
374    if !relate_core::tokens::workspace_accounting() || !s.batch.created_nodes.contains(&id) {
375        return None;
376    }
377    s.batch
378        .nodes
379        .get(&id)
380        .map(|node| crate::workspace::created_label_bytes(&node.labels))
381}
382
383fn shift_created_labels(s: &mut WriteScratch, id: NodeId, before: Option<u64>) {
384    let Some(before) = before else {
385        return;
386    };
387    let Some(after) = s
388        .batch
389        .nodes
390        .get(&id)
391        .map(|node| crate::workspace::created_label_bytes(&node.labels))
392    else {
393        return;
394    };
395    s.shift_workspace(before, after);
396}
397
398fn created_property_snapshot(s: &WriteScratch, id: NodeId, created: bool) -> Option<u64> {
399    if !created || !relate_core::tokens::workspace_accounting() {
400        return None;
401    }
402    s.batch
403        .nodes
404        .get(&id)
405        .map(|node| crate::workspace::created_property_delta(&node.properties))
406}
407
408fn shift_created_properties(s: &mut WriteScratch, id: NodeId, before: Option<u64>) {
409    let Some(before) = before else {
410        return;
411    };
412    let Some(after) = s
413        .batch
414        .nodes
415        .get(&id)
416        .map(|node| crate::workspace::created_property_delta(&node.properties))
417    else {
418        return;
419    };
420    s.shift_workspace(before, after);
421}
422
423fn created_rel_property_snapshot(s: &WriteScratch, id: RelId, created: bool) -> Option<u64> {
424    if !created || !relate_core::tokens::workspace_accounting() {
425        return None;
426    }
427    s.batch
428        .rels
429        .get(&id)
430        .map(|rel| crate::workspace::created_property_delta(&rel.properties))
431}
432
433fn shift_created_rel_properties(s: &mut WriteScratch, id: RelId, before: Option<u64>) {
434    let Some(before) = before else {
435        return;
436    };
437    let Some(after) = s
438        .batch
439        .rels
440        .get(&id)
441        .map(|rel| crate::workspace::created_property_delta(&rel.properties))
442    else {
443        return;
444    };
445    s.shift_workspace(before, after);
446}
447
448fn created_rel_removal(s: &WriteScratch, id: RelId) -> Option<u64> {
449    if !relate_core::tokens::workspace_accounting() || !s.batch.created_rels.contains(&id) {
450        return None;
451    }
452    s.batch.rels.get(&id).map(|rel| {
453        crate::workspace::created_rel_remove_delta(
454            s.batch.created_rels.len().saturating_sub(1),
455            rel,
456        )
457    })
458}
459
460fn created_node_removal(s: &WriteScratch, id: NodeId) -> Option<u64> {
461    if !relate_core::tokens::workspace_accounting() || !s.batch.created_nodes.contains(&id) {
462        return None;
463    }
464    s.batch.nodes.get(&id).map(|node| {
465        crate::workspace::created_node_remove_delta(
466            s.batch.created_nodes.len().saturating_sub(1),
467            node,
468        )
469    })
470}
471
472/// The redo-op payload of one set_property, before the node/rel verb wraps
473/// it into its [`RedoOp`] variant.
474enum PropOpKind {
475    Set(String, Value),
476    Remove(String),
477}
478
479/// The shared core of `set_property_node`/`set_property_rel`: apply the
480/// null-means-remove / otherwise-upsert contract to one properties map and
481/// report the stats deltas plus the redo-op payload. A null value removing
482/// an absent key is a no-op (no deltas, no op).
483fn set_prop_core(
484    props: &mut relate_core::PropertyMap,
485    created: bool,
486    key: &str,
487    value: &Value,
488) -> ((i64, i64), Option<PropOpKind>) {
489    if value.is_null() {
490        if props.remove(key).is_some() {
491            return ((0, 1), Some(PropOpKind::Remove(key.to_string())));
492        }
493        return ((0, 0), None);
494    }
495    let existed = props.contains_key(key);
496    props.insert(key.to_string(), value.clone());
497    (
498        prop_stat_deltas(existed, created),
499        Some(PropOpKind::Set(key.to_string(), value.clone())),
500    )
501}
502
503/// The shared core of `replace_properties_*`: null out every current key the
504/// map does not name, then set every entry, all through the one setter.
505fn replace_props(
506    keys: Vec<String>,
507    map: BTreeMap<String, Value>,
508    mut set: impl FnMut(&str, Value),
509) {
510    for k in &keys {
511        if !map.contains_key(k) {
512            set(k, Value::Null);
513        }
514    }
515    for (k, v) in map {
516        set(&k, v);
517    }
518}
519
520/// Stats deltas for a set_property on a pre-existing (or CREATE-added) map:
521/// overwriting an existing key counts set+removed; a fresh key counts set;
522/// CREATE already counting the key (`created` on an `existed` map cell) is
523/// the no-op.
524fn prop_stat_deltas(existed: bool, created: bool) -> (i64, i64) {
525    if existed && !created {
526        (1, 1)
527    } else if !existed {
528        (1, 0)
529    } else {
530        (0, 0)
531    }
532}