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 created = s.batch.created_nodes.contains(&id);
168        let shift = CreatedShift::begin(&s, created, node_label_bytes(id));
169        let mut added = Vec::new();
170        if let Some(n) = Self::cow_node(&mut s, self.base, id) {
171            std::sync::Arc::make_mut(&mut n.labels).extend(fresh.iter().cloned());
172            added = fresh;
173        }
174        shift.finish(&mut s);
175        s.net_label_stats(labels_added, labels_removed);
176        if !added.is_empty() {
177            s.bump_live_labels(&added, 1);
178            s.push_redo(RedoOp::add_labels(id, added));
179        }
180    }
181
182    pub fn remove_labels(&self, id: NodeId, labels: &[String]) {
183        // Cow the node first and derive everything from `n.labels` in one
184        // pass: `extract_if` walks the node's labels once, dropping the
185        // ones the request names and collecting them into `actually` in
186        // node order. `requested` answers membership in O(1) per node
187        // label; `actually` feeds the accounting and the live-label bump
188        // (both consumers dedupe, so node order is as good as request
189        // order). A missing or scratch-deleted node leaves `actually`
190        // empty, exactly what the pre-cow read answered for it.
191        let requested: HashSet<&str> = labels.iter().map(String::as_str).collect();
192        let mut s = self.scratch_mut();
193        let created = s.batch.created_nodes.contains(&id);
194        let shift = CreatedShift::begin(&s, created, node_label_bytes(id));
195        let mut actually: Vec<String> = Vec::new();
196        if let Some(n) = Self::cow_node(&mut s, self.base, id) {
197            actually = std::sync::Arc::make_mut(&mut n.labels)
198                .extract_if(.., |l| requested.contains(l.as_str()))
199                .collect();
200        }
201        shift.finish(&mut s);
202        let (labels_added, labels_removed) = self.label_deltas(&s, &actually, LabelChange::Loss);
203        s.net_label_stats(labels_added, labels_removed);
204        if !actually.is_empty() {
205            s.bump_live_labels(&actually, -1);
206            // The op carries the labels the node actually lost, so the
207            // ADR-0309 per-node count is derived from it (a requested label
208            // the node did not carry is a no-op).
209            s.push_redo(RedoOp::remove_labels(id, actually));
210        }
211    }
212
213    /// CIP-162 overwrite semantics, spelled once beside the primitives it
214    /// composes: the node's labels become exactly `labels` — the ones it
215    /// carries but the list omits leave ([`remove_labels`]), then the
216    /// list's labels arrive ([`add_labels`]). Each half keeps its own
217    /// accounting and redo, so the overwrite is their compose, not a third
218    /// label-write path.
219    pub fn set_labels(&self, id: NodeId, labels: &[String]) {
220        let current = self.node_labels(id).unwrap_or_default();
221        let remove: Vec<String> = current
222            .into_iter()
223            .filter(|label| !labels.contains(label))
224            .collect();
225        // An empty diff skips the remove half (mirroring add_labels' own
226        // empty-list guard) instead of cowing the node for nothing.
227        if !remove.is_empty() {
228            self.remove_labels(id, &remove);
229        }
230        self.add_labels(id, labels);
231    }
232
233    pub fn set_property_node(&self, id: NodeId, key: &str, value: Value) {
234        let mut s = self.scratch_mut();
235        let created = s.batch.created_nodes.contains(&id);
236        let shift = CreatedShift::begin(&s, created, node_property_bytes(id));
237        let outcome = Self::cow_node(&mut s, self.base, id).map(|n| {
238            set_prop_core(
239                std::sync::Arc::make_mut(&mut n.properties),
240                created,
241                key,
242                &value,
243            )
244        });
245        shift.finish(&mut s);
246        finish_set_property(&mut s, outcome, |op| match op {
247            PropOpKind::Set(k, v) => RedoOp::set_node_prop(id, k, v),
248            PropOpKind::Remove(k) => RedoOp::remove_node_prop(id, k),
249        });
250    }
251
252    pub fn set_property_rel(&self, id: RelId, key: &str, value: Value) {
253        let mut s = self.scratch_mut();
254        let created = s.batch.created_rels.contains(&id);
255        let shift = CreatedShift::begin(&s, created, rel_property_bytes(id));
256        let outcome = Self::cow_rel(&mut s, self.base, id).map(|r| {
257            set_prop_core(
258                std::sync::Arc::make_mut(&mut r.properties),
259                created,
260                key,
261                &value,
262            )
263        });
264        shift.finish(&mut s);
265        finish_set_property(&mut s, outcome, |op| match op {
266            PropOpKind::Set(k, v) => RedoOp::set_rel_prop(id, k, v),
267            PropOpKind::Remove(k) => RedoOp::remove_rel_prop(id, k),
268        });
269    }
270
271    /// `SET n += map`: per-key merge through the set verb (an existing
272    /// key keeps its position, a new one is added) — the node and
273    /// relationship forms are the same loop over their set verbs.
274    pub fn merge_properties_node(&self, id: NodeId, map: &BTreeMap<String, Value>) {
275        for (k, v) in map {
276            self.set_property_node(id, k, v.clone());
277        }
278    }
279
280    /// The relationship form of [`Self::merge_properties_node`].
281    pub fn merge_properties_rel(&self, id: RelId, map: &BTreeMap<String, Value>) {
282        for (k, v) in map {
283            self.set_property_rel(id, k, v.clone());
284        }
285    }
286
287    pub fn replace_properties_node(&self, id: NodeId, map: BTreeMap<String, Value>) {
288        let keys: Vec<String> = self
289            .node(id)
290            .map(|n| n.properties.keys().cloned().collect())
291            .unwrap_or_default();
292        replace_props(keys, map, |k, v| self.set_property_node(id, k, v));
293    }
294
295    pub fn replace_properties_rel(&self, id: RelId, map: BTreeMap<String, Value>) {
296        let keys: Vec<String> = self
297            .rel(id)
298            .map(|r| r.properties.keys().cloned().collect())
299            .unwrap_or_default();
300        replace_props(keys, map, |k, v| self.set_property_rel(id, k, v));
301    }
302
303    pub fn delete_rel(&self, id: RelId) {
304        let nprops = match self.rel(id) {
305            Some(r) => r.properties.len() as i64,
306            None => return,
307        };
308        let mut s = self.scratch_mut();
309        let removed = created_rel_removal(&s, id);
310        s.batch.deleted_rels.insert(id);
311        s.batch.rels.remove(&id);
312        if s.batch.created_rels.remove(&id) {
313            if let Some(delta) = removed {
314                s.shift_workspace(delta, 0);
315            }
316            s.statement.stats.relationships_created =
317                s.statement.stats.relationships_created.saturating_sub(1);
318            s.statement.stats.properties_set =
319                s.statement.stats.properties_set.saturating_sub(nprops);
320        } else {
321            s.statement.stats.relationships_deleted += 1;
322            s.statement.stats.properties_removed += nprops;
323        }
324        s.push_redo(RedoOp::delete_rel(id));
325    }
326
327    pub fn delete_node(&self, id: NodeId, detach: bool) -> Result<()> {
328        let incident: Vec<RelId> = self.neighbors(id, Direction::Both);
329        if !detach && !incident.is_empty() {
330            return Err(crate::graph::delete_connected_node_error());
331        }
332        for rid in &incident {
333            self.delete_rel(*rid);
334        }
335        // One fetch answers both "is the node live" and "what does it
336        // carry": a missing node has nothing to delete.
337        let Some(node) = self.node(id) else {
338            return Ok(());
339        };
340        let nprops = node.properties.len() as i64;
341        let labels = node.labels;
342        let mut s = self.scratch_mut();
343        let (labels_added, labels_removed) = self.label_deltas(&s, &labels, LabelChange::Loss);
344        let removed = created_node_removal(&s, id);
345        s.batch.deleted_nodes.insert(id);
346        s.batch.nodes.remove(&id);
347        s.bump_live_labels(&labels, -1);
348        s.net_label_stats(labels_added, labels_removed);
349        if s.batch.created_nodes.remove(&id) {
350            if let Some(delta) = removed {
351                s.shift_workspace(delta, 0);
352            }
353            s.statement.stats.nodes_created = s.statement.stats.nodes_created.saturating_sub(1);
354            s.statement.stats.properties_set =
355                s.statement.stats.properties_set.saturating_sub(nprops);
356        } else {
357            s.statement.stats.nodes_deleted += 1;
358            s.statement.stats.properties_removed += nprops;
359        }
360        s.push_redo(RedoOp::delete_node(id));
361        Ok(())
362    }
363}
364
365/// The workspace bytes the created node `id`'s labels hold now, `None`
366/// when the scratch has no copy of it.
367fn node_label_bytes(id: NodeId) -> impl Fn(&WriteScratch) -> Option<u64> {
368    move |s| {
369        s.batch
370            .nodes
371            .get(&id)
372            .map(|node| crate::workspace::created_label_bytes(&node.labels))
373    }
374}
375
376/// The workspace bytes the created node `id`'s properties hold now.
377fn node_property_bytes(id: NodeId) -> impl Fn(&WriteScratch) -> Option<u64> {
378    move |s| {
379        s.batch
380            .nodes
381            .get(&id)
382            .map(|node| crate::workspace::created_property_delta(&node.properties))
383    }
384}
385
386/// The workspace bytes the created relationship `id`'s properties hold now.
387fn rel_property_bytes(id: RelId) -> impl Fn(&WriteScratch) -> Option<u64> {
388    move |s| {
389        s.batch
390            .rels
391            .get(&id)
392            .map(|rel| crate::workspace::created_property_delta(&rel.properties))
393    }
394}
395
396/// The created-entity workspace shift as one guard: [`Self::begin`] snapshots
397/// the bytes `bytes` reads off the scratch copy (only when workspace
398/// accounting is on and the entity was created in this batch), and
399/// [`Self::finish`] re-reads them after the write and shifts the workspace
400/// by the difference. A snapshot exists only for an entity the scratch
401/// already held, and the cow never removes it.
402struct CreatedShift<F: Fn(&WriteScratch) -> Option<u64>> {
403    before: Option<u64>,
404    bytes: F,
405}
406
407impl<F: Fn(&WriteScratch) -> Option<u64>> CreatedShift<F> {
408    fn begin(s: &WriteScratch, created: bool, bytes: F) -> Self {
409        let before = if created && relate_core::tokens::workspace_accounting() {
410            bytes(s)
411        } else {
412            None
413        };
414        Self { before, bytes }
415    }
416
417    fn finish(self, s: &mut WriteScratch) {
418        let Some(before) = self.before else {
419            return;
420        };
421        let after = (self.bytes)(s).expect("the cow inserted the scratch copy");
422        s.shift_workspace(before, after);
423    }
424}
425
426/// The stats + redo tail `set_property_node`/`set_property_rel` share: fold
427/// the write's deltas into the statement stats and push the redo op the
428/// caller's constructor builds from the payload.
429fn finish_set_property(
430    s: &mut WriteScratch,
431    outcome: Option<PropWrite>,
432    redo: impl FnOnce(PropOpKind) -> RedoOp,
433) {
434    // A missing or scratch-deleted entity (no cow copy) is a no-op write.
435    let Some(PropWrite { set, removed, op }) = outcome else {
436        return;
437    };
438    s.statement.stats.properties_set += set;
439    s.statement.stats.properties_removed += removed;
440    if let Some(op) = op {
441        s.push_redo(redo(op));
442    }
443}
444
445fn created_rel_removal(s: &WriteScratch, id: RelId) -> Option<u64> {
446    if !relate_core::tokens::workspace_accounting() || !s.batch.created_rels.contains(&id) {
447        return None;
448    }
449    s.batch.rels.get(&id).map(|rel| {
450        crate::workspace::created_rel_remove_delta(
451            s.batch.created_rels.len().saturating_sub(1),
452            rel,
453        )
454    })
455}
456
457fn created_node_removal(s: &WriteScratch, id: NodeId) -> Option<u64> {
458    if !relate_core::tokens::workspace_accounting() || !s.batch.created_nodes.contains(&id) {
459        return None;
460    }
461    s.batch.nodes.get(&id).map(|node| {
462        crate::workspace::created_node_remove_delta(
463            s.batch.created_nodes.len().saturating_sub(1),
464            node,
465        )
466    })
467}
468
469/// The redo-op payload of one set_property, before the node/rel verb wraps
470/// it into its [`RedoOp`] variant.
471enum PropOpKind {
472    Set(String, Value),
473    Remove(String),
474}
475
476/// What one set_property did: the stats deltas plus the redo-op payload.
477#[derive(Default)]
478struct PropWrite {
479    set: i64,
480    removed: i64,
481    op: Option<PropOpKind>,
482}
483
484/// The shared core of `set_property_node`/`set_property_rel`: apply the
485/// null-means-remove / otherwise-upsert contract to one properties map and
486/// report the stats deltas plus the redo-op payload. A null value removing
487/// an absent key is a no-op (no deltas, no op).
488fn set_prop_core(
489    props: &mut relate_core::PropertyMap,
490    created: bool,
491    key: &str,
492    value: &Value,
493) -> PropWrite {
494    if value.is_null() {
495        if props.remove(key).is_some() {
496            return PropWrite {
497                set: 0,
498                removed: 1,
499                op: Some(PropOpKind::Remove(key.to_string())),
500            };
501        }
502        return PropWrite::default();
503    }
504    let existed = props.contains_key(key);
505    props.insert(key.to_string(), value.clone());
506    let (set, removed) = prop_stat_deltas(existed, created);
507    PropWrite {
508        set,
509        removed,
510        op: Some(PropOpKind::Set(key.to_string(), value.clone())),
511    }
512}
513
514/// The shared core of `replace_properties_*`: null out every current key the
515/// map does not name, then set every entry, all through the one setter.
516fn replace_props(
517    keys: Vec<String>,
518    map: BTreeMap<String, Value>,
519    mut set: impl FnMut(&str, Value),
520) {
521    for k in &keys {
522        if !map.contains_key(k) {
523            set(k, Value::Null);
524        }
525    }
526    for (k, v) in map {
527        set(&k, v);
528    }
529}
530
531/// Stats deltas for a set_property on a pre-existing (or CREATE-added) map:
532/// overwriting an existing key counts set+removed; a fresh key counts set;
533/// CREATE already counting the key (`created` on an `existed` map cell) is
534/// the no-op.
535fn prop_stat_deltas(existed: bool, created: bool) -> (i64, i64) {
536    if existed && !created {
537        (1, 1)
538    } else if !existed {
539        (1, 0)
540    } else {
541        (0, 0)
542    }
543}