relate-executor 1.4.0

In-memory graph and Cypher physical executor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! The write verbs: every overlay mutation (`create_node`, `create_rel`,
//! `add_labels`/`remove_labels`, the `set_property_*` /
//! `merge_properties_*` / `replace_properties_*` family, `delete_*`)
//! funnels through [`WriteScratch::push_redo`], so the redo log and the
//! lazy equality indexes stay current for every write. Stats accounting
//! (creates, deletes, properties set/removed, net label deltas) happens
//! here, next to the mutation it counts: the openCypher graph-diff
//! counters (net new label names, property set/removed pairs) and Neo4j's
//! update counters beside them (labels per node, one property write per
//! write, ADR-0309).

use std::collections::{BTreeMap, HashSet};

use relate_core::{Node, NodeId, RelId, Relationship, Result, Value};
use relate_ir::Direction;

use crate::graph::{EntityId, Graph};
use crate::redo::RedoOp;

use super::label_probe::LabelChange;
use super::{distinct_labels, ExecGraph, WriteScratch};

impl ExecGraph<'_> {
    pub fn create_node(
        &self,
        labels: Vec<String>,
        properties: BTreeMap<String, Value>,
    ) -> Result<NodeId> {
        let mut s = self.scratch_mut();
        let labels = std::sync::Arc::new(labels);
        let properties = std::sync::Arc::new(relate_core::PropertyMap::from(properties));
        let (labels_added, labels_removed) = self.label_deltas(&s, &labels, LabelChange::Gain);
        s.reserve_new_node(&Node {
            id: 0,
            labels: std::sync::Arc::clone(&labels),
            properties: std::sync::Arc::clone(&properties),
        })?;
        let id = s.alloc_node()?;
        s.statement.stats.nodes_created += 1;
        s.net_label_stats(labels_added, labels_removed);
        s.statement.stats.properties_set += properties.len() as i64;
        s.batch.nodes.insert(
            id,
            Node {
                id,
                labels: std::sync::Arc::clone(&labels),
                properties: std::sync::Arc::clone(&properties),
            },
        );
        s.batch.bump_live_labels(&labels, 1);
        s.push_redo(RedoOp::CreateNode {
            id,
            labels,
            properties,
        });
        drop(s);
        relate_core::tokens::poll()?;
        Ok(id)
    }

    pub fn create_rel(
        &self,
        start: NodeId,
        end: NodeId,
        rel_type: String,
        properties: BTreeMap<String, Value>,
    ) -> Result<RelId> {
        if !self.node_exists(start) || !self.node_exists(end) {
            return Err(crate::graph::missing_rel_endpoint_error());
        }
        let properties = std::sync::Arc::new(relate_core::PropertyMap::from(properties));
        let mut s = self.scratch_mut();
        s.reserve_new_rel(&Relationship {
            id: 0,
            start,
            end,
            rel_type: rel_type.clone(),
            properties: std::sync::Arc::clone(&properties),
        })?;
        let id = s.alloc_rel()?;
        s.statement.stats.relationships_created += 1;
        s.statement.stats.properties_set += properties.len() as i64;
        s.batch.rels.insert(
            id,
            Relationship {
                id,
                start,
                end,
                rel_type: rel_type.clone(),
                properties: std::sync::Arc::clone(&properties),
            },
        );
        s.batch.out_adj.entry(start).or_default().push(id);
        s.batch.in_adj.entry(end).or_default().push(id);
        s.push_redo(RedoOp::CreateRel {
            id,
            start,
            end,
            rel_type,
            properties,
        });
        drop(s);
        relate_core::tokens::poll()?;
        Ok(id)
    }

    fn cow_node<'b>(s: &'b mut WriteScratch, base: &Graph, id: NodeId) -> Option<&'b mut Node> {
        if s.batch.deleted_nodes.contains(&id) {
            return None;
        }
        if !s.batch.nodes.contains_key(&id) {
            let n = base.node_at(id, s.snapshot_ts())?;
            // LABS-1085 review: a copy-on-write introduces the base node
            // into the scratch, so its whole label/property vocabulary
            // posts into the equality index — exactly what a create
            // posts. Without this, a pair built before the cow misses
            // the node's pre-existing properties, and a keyed lookup
            // (MERGE's match arm) silently misses the node and creates
            // a duplicate. Set/label ops on the copy post on top;
            // postings are sets, so a double post is harmless.
            for (key, value) in &*n.properties {
                s.batch.prop_ix.post_value(id, &n.labels, key, value);
            }
            s.batch.nodes.insert(id, n);
        }
        s.batch.nodes.get_mut(&id)
    }

    fn cow_rel<'b>(
        s: &'b mut WriteScratch,
        base: &Graph,
        id: RelId,
    ) -> Option<&'b mut Relationship> {
        if s.batch.deleted_rels.contains(&id) {
            return None;
        }
        if !s.batch.rels.contains_key(&id) {
            let r = base.rel_at(id, s.snapshot_ts())?;
            // The node cow's posting contract (above), on the rel index.
            for (key, value) in &*r.properties {
                s.batch.rel_prop_ix.post_value(id, &r.rel_type, key, value);
            }
            s.batch.rels.insert(id, r);
        }
        s.batch.rels.get_mut(&id)
    }

    pub fn add_labels(&self, id: NodeId, labels: &[String]) {
        if labels.is_empty() {
            return;
        }
        let existing = self.node_labels(id).unwrap_or_default();
        // The labels this write actually adds: the distinct requested labels
        // not already on the node, in first-occurrence order. Computed once
        // and reused for the accounting and the cow block; `n.labels ==
        // existing` at cow time, so the cow block pushes `fresh` as-is
        // instead of re-answering the membership question per label.
        let fresh: Vec<String> = distinct_labels(labels)
            .into_iter()
            .filter(|l| !existing.iter().any(|x| x == *l))
            .map(str::to_string)
            .collect();
        let mut s = self.scratch_mut();
        let created = s.batch.created_nodes.contains(&id);
        let shift = CreatedShift::begin(&s, created, node_label_bytes(id));
        let mut added = Vec::new();
        if let Some(n) = Self::cow_node(&mut s, self.base, id) {
            std::sync::Arc::make_mut(&mut n.labels).extend(fresh.iter().cloned());
            added = fresh;
        }
        shift.finish(&mut s);
        // Accounted from the applied set (`added`), like remove_labels: a
        // missing or scratch-deleted node applies nothing and counts nothing.
        let (labels_added, labels_removed) = self.label_deltas(&s, &added, LabelChange::Gain);
        s.net_label_stats(labels_added, labels_removed);
        if !added.is_empty() {
            s.batch.bump_live_labels(&added, 1);
            s.push_redo(RedoOp::add_labels(id, added));
        }
    }

    pub fn remove_labels(&self, id: NodeId, labels: &[String]) {
        // Cow the node first and derive everything from `n.labels` in one
        // pass: `extract_if` walks the node's labels once, dropping the
        // ones the request names and collecting them into `actually` in
        // node order. `requested` answers membership in O(1) per node
        // label; `actually` feeds the accounting and the live-label bump
        // (both consumers dedupe, so node order is as good as request
        // order). A missing or scratch-deleted node leaves `actually`
        // empty, exactly what the pre-cow read answered for it.
        let requested: HashSet<&str> = labels.iter().map(String::as_str).collect();
        let mut s = self.scratch_mut();
        let created = s.batch.created_nodes.contains(&id);
        let shift = CreatedShift::begin(&s, created, node_label_bytes(id));
        let mut actually: Vec<String> = Vec::new();
        if let Some(n) = Self::cow_node(&mut s, self.base, id) {
            actually = std::sync::Arc::make_mut(&mut n.labels)
                .extract_if(.., |l| requested.contains(l.as_str()))
                .collect();
        }
        shift.finish(&mut s);
        let (labels_added, labels_removed) = self.label_deltas(&s, &actually, LabelChange::Loss);
        s.net_label_stats(labels_added, labels_removed);
        if !actually.is_empty() {
            s.batch.bump_live_labels(&actually, -1);
            // The op carries the labels the node actually lost, so the
            // ADR-0309 per-node count is derived from it (a requested label
            // the node did not carry is a no-op).
            s.push_redo(RedoOp::remove_labels(id, actually));
        }
    }

    /// CIP-162 overwrite semantics, spelled once beside the primitives it
    /// composes: the node's labels become exactly `labels` — the ones it
    /// carries but the list omits leave ([`remove_labels`]), then the
    /// list's labels arrive ([`add_labels`]). Each half keeps its own
    /// accounting and redo, so the overwrite is their compose, not a third
    /// label-write path.
    pub fn set_labels(&self, id: NodeId, labels: &[String]) {
        let current = self.node_labels(id).unwrap_or_default();
        let remove: Vec<String> = current
            .into_iter()
            .filter(|label| !labels.contains(label))
            .collect();
        // An empty diff skips the remove half (mirroring add_labels' own
        // empty-list guard) instead of cowing the node for nothing.
        if !remove.is_empty() {
            self.remove_labels(id, &remove);
        }
        self.add_labels(id, labels);
    }

    pub fn set_property_node(&self, id: NodeId, key: &str, value: Value) {
        let mut s = self.scratch_mut();
        let created = s.batch.created_nodes.contains(&id);
        let shift = CreatedShift::begin(&s, created, node_property_bytes(id));
        let outcome = Self::cow_node(&mut s, self.base, id).map(|n| {
            set_prop_core(
                std::sync::Arc::make_mut(&mut n.properties),
                created,
                key,
                &value,
            )
        });
        shift.finish(&mut s);
        finish_set_property(&mut s, outcome, |op| match op {
            PropOpKind::Set(k, v) => RedoOp::set_node_prop(id, k, v),
            PropOpKind::Remove(k) => RedoOp::remove_node_prop(id, k),
        });
    }

    pub fn set_property_rel(&self, id: RelId, key: &str, value: Value) {
        let mut s = self.scratch_mut();
        let created = s.batch.created_rels.contains(&id);
        let shift = CreatedShift::begin(&s, created, rel_property_bytes(id));
        let outcome = Self::cow_rel(&mut s, self.base, id).map(|r| {
            set_prop_core(
                std::sync::Arc::make_mut(&mut r.properties),
                created,
                key,
                &value,
            )
        });
        shift.finish(&mut s);
        finish_set_property(&mut s, outcome, |op| match op {
            PropOpKind::Set(k, v) => RedoOp::set_rel_prop(id, k, v),
            PropOpKind::Remove(k) => RedoOp::remove_rel_prop(id, k),
        });
    }

    /// `SET n += map`: per-key merge through the set verb (an existing
    /// key keeps its position, a new one is added) — the node and
    /// relationship forms are the same loop over their set verbs.
    pub fn merge_properties_node(&self, id: NodeId, map: &BTreeMap<String, Value>) {
        for (k, v) in map {
            self.set_property_node(id, k, v.clone());
        }
    }

    /// The relationship form of [`Self::merge_properties_node`].
    pub fn merge_properties_rel(&self, id: RelId, map: &BTreeMap<String, Value>) {
        for (k, v) in map {
            self.set_property_rel(id, k, v.clone());
        }
    }

    pub fn replace_properties_node(&self, id: NodeId, map: BTreeMap<String, Value>) {
        let keys: Vec<String> = self
            .node(id)
            .map(|n| n.properties.keys().cloned().collect())
            .unwrap_or_default();
        replace_props(keys, map, |k, v| self.set_property_node(id, k, v));
    }

    pub fn replace_properties_rel(&self, id: RelId, map: BTreeMap<String, Value>) {
        let keys: Vec<String> = self
            .rel(id)
            .map(|r| r.properties.keys().cloned().collect())
            .unwrap_or_default();
        replace_props(keys, map, |k, v| self.set_property_rel(id, k, v));
    }

    /// The kind-addressed forms of the three property verbs a resolved
    /// write drives: the `EntityId` selector lives here once, so no write
    /// arm re-opens a `match entity { Node => …_node, Rel => …_rel }` of
    /// its own.
    pub(crate) fn set_property(&self, entity: EntityId, key: &str, value: Value) {
        match entity {
            EntityId::Node(id) => self.set_property_node(id, key, value),
            EntityId::Rel(id) => self.set_property_rel(id, key, value),
        }
    }

    /// [`Self::set_property`]'s full-replacement form.
    pub(crate) fn replace_properties(&self, entity: EntityId, map: BTreeMap<String, Value>) {
        match entity {
            EntityId::Node(id) => self.replace_properties_node(id, map),
            EntityId::Rel(id) => self.replace_properties_rel(id, map),
        }
    }

    /// [`Self::set_property`]'s per-key merge form.
    pub(crate) fn merge_properties(&self, entity: EntityId, map: &BTreeMap<String, Value>) {
        match entity {
            EntityId::Node(id) => self.merge_properties_node(id, map),
            EntityId::Rel(id) => self.merge_properties_rel(id, map),
        }
    }

    pub fn delete_rel(&self, id: RelId) {
        // One fetch answers both "is the rel live" and "what it carries":
        // a missing rel has nothing to delete (the `let … else` twin of
        // `delete_node`'s form).
        let Some(r) = self.rel(id) else { return };
        let nprops = r.properties.len() as i64;
        let mut s = self.scratch_mut();
        release_created(&mut s, EntityId::Rel(id));
        s.batch.deleted_rels.insert(id);
        net_or_count_delete(&mut s, EntityId::Rel(id), nprops);
        s.push_redo(RedoOp::delete_rel(id));
    }

    pub fn delete_node(&self, id: NodeId, detach: bool) -> Result<()> {
        let incident: Vec<RelId> = self.neighbors(id, Direction::Both);
        if !detach && !incident.is_empty() {
            return Err(crate::graph::delete_connected_node_error());
        }
        for rid in &incident {
            self.delete_rel(*rid);
        }
        // One fetch answers both "is the node live" and "what does it
        // carry": a missing node has nothing to delete.
        let Some(node) = self.node(id) else {
            return Ok(());
        };
        let nprops = node.properties.len() as i64;
        let labels = node.labels;
        let mut s = self.scratch_mut();
        let (labels_added, labels_removed) = self.label_deltas(&s, &labels, LabelChange::Loss);
        release_created(&mut s, EntityId::Node(id));
        s.batch.deleted_nodes.insert(id);
        s.batch.bump_live_labels(&labels, -1);
        s.net_label_stats(labels_added, labels_removed);
        net_or_count_delete(&mut s, EntityId::Node(id), nprops);
        s.push_redo(RedoOp::delete_node(id));
        Ok(())
    }
}

/// The per-kind state one delete nets against (REL8-1188): the statement-local
/// created set's verdict plus the four counter targets the decision writes.
/// One bundle per kind, so the node/rel vocabulary is dispatched exactly once.
struct DeleteNets<'a> {
    statement_created: bool,
    created: &'a mut i64,
    set: &'a mut i64,
    deleted: &'a mut i64,
    removed: &'a mut i64,
}

/// The net-or-count decision both delete verbs share (REL8-1188). A delete
/// nets the create's counters only for an entity *this statement* created in
/// the batch it is deleting in — the id is still in the statement-local
/// created set, which a batch rebase clears together with the batch's own
/// charged created set ([`WriteScratch::rebase`]) — so a create/delete pair
/// inside one statement cancels (the pinned
/// `create_then_delete_cancels_create_stats` model). Every other delete
/// counts as this statement's delete: of a pre-existing entity, of one an
/// earlier statement of the transaction created (the create was counted by
/// that statement, so netting here would drive the counter negative and
/// poison every binding through the wire-stats boundary), or of one an
/// earlier batch of this batched statement already committed
/// (`CALL { … } IN TRANSACTIONS`, ADR-0210 — the committed create and the
/// delete both report).
fn net_or_count_delete(s: &mut WriteScratch, entity: EntityId, nprops: i64) {
    let nets = match entity {
        EntityId::Node(id) => DeleteNets {
            statement_created: s.statement.created_nodes.remove(&id),
            created: &mut s.statement.stats.nodes_created,
            set: &mut s.statement.stats.properties_set,
            deleted: &mut s.statement.stats.nodes_deleted,
            removed: &mut s.statement.stats.properties_removed,
        },
        EntityId::Rel(id) => DeleteNets {
            statement_created: s.statement.created_rels.remove(&id),
            created: &mut s.statement.stats.relationships_created,
            set: &mut s.statement.stats.properties_set,
            deleted: &mut s.statement.stats.relationships_deleted,
            removed: &mut s.statement.stats.properties_removed,
        },
    };
    if nets.statement_created {
        // The statement counted this create, so both counters still hold it:
        // every property the entity carries was counted at the create or by a
        // later write. `checked_sub` + the named expect keep a broken
        // statement-created fact from the silent `saturating_sub` clamp that
        // was the REL8-1188 bug; the i64 floor is refused here, and
        // non-negativity is tripped where it is owned — the wire boundary's
        // own expect (`relate::query_stats_to_wire`).
        *nets.created = nets
            .created
            .checked_sub(1)
            .expect("a statement-created entity's create counter still holds it");
        *nets.set = nets
            .set
            .checked_sub(nprops)
            .expect("a statement-created entity's property counter still holds it");
    } else {
        *nets.deleted += 1;
        *nets.removed += nprops;
    }
}

/// The workspace bytes the created node `id`'s labels hold now, `None`
/// when the scratch has no copy of it.
fn node_label_bytes(id: NodeId) -> impl Fn(&WriteScratch) -> Option<u64> {
    move |s| {
        s.batch
            .nodes
            .get(&id)
            .map(|node| crate::workspace::created_label_bytes(&node.labels))
    }
}

/// The workspace bytes the created node `id`'s properties hold now.
fn node_property_bytes(id: NodeId) -> impl Fn(&WriteScratch) -> Option<u64> {
    move |s| {
        s.batch
            .nodes
            .get(&id)
            .map(|node| crate::workspace::created_property_delta(&node.properties))
    }
}

/// The workspace bytes the created relationship `id`'s properties hold now.
fn rel_property_bytes(id: RelId) -> impl Fn(&WriteScratch) -> Option<u64> {
    move |s| {
        s.batch
            .rels
            .get(&id)
            .map(|rel| crate::workspace::created_property_delta(&rel.properties))
    }
}

/// The created-entity workspace shift as one guard: [`Self::begin`] snapshots
/// the bytes `bytes` reads off the scratch copy (only when workspace
/// accounting is on and the entity was created in this batch), and
/// [`Self::finish`] re-reads them after the write and shifts the workspace
/// by the difference. A snapshot exists only for an entity the scratch
/// already held, and the cow never removes it.
struct CreatedShift<F: Fn(&WriteScratch) -> Option<u64>> {
    before: Option<u64>,
    bytes: F,
}

impl<F: Fn(&WriteScratch) -> Option<u64>> CreatedShift<F> {
    fn begin(s: &WriteScratch, created: bool, bytes: F) -> Self {
        let before = if created && relate_core::tokens::workspace_accounting() {
            bytes(s)
        } else {
            None
        };
        Self { before, bytes }
    }

    fn finish(self, s: &mut WriteScratch) {
        let Some(before) = self.before else {
            return;
        };
        let after = (self.bytes)(s).expect("the cow inserted the scratch copy");
        s.shift_workspace(before, after);
    }
}

/// The stats + redo tail `set_property_node`/`set_property_rel` share: fold
/// the write's deltas into the statement stats and push the redo op the
/// caller's constructor builds from the payload.
fn finish_set_property(
    s: &mut WriteScratch,
    outcome: Option<PropWrite>,
    redo: impl FnOnce(PropOpKind) -> RedoOp,
) {
    // A missing or scratch-deleted entity (no cow copy) is a no-op write.
    let Some(PropWrite { set, removed, op }) = outcome else {
        return;
    };
    s.statement.stats.properties_set += set;
    s.statement.stats.properties_removed += removed;
    if let Some(op) = op {
        s.push_redo(redo(op));
    }
}

/// The bookkeeping half of one delete, dispatched once per kind on
/// [`EntityId`] (the same vocabulary [`net_or_count_delete`] reads): drop
/// the entity's batch-set membership and take its scratch copy out — both
/// unconditional, so the charged set never retains a deleted id — then
/// release the copy's workspace charge when this batch created it. The
/// write direction of the same charge is the `CreatedShift` pair beside
/// this; a pre-existing entity's copy (a copy-on-write edit) was never
/// charged as a create, so its delete releases nothing.
fn release_created(s: &mut WriteScratch, entity: EntityId) {
    match entity {
        EntityId::Node(id) => {
            let batch_created = s.batch.created_nodes.remove(&id);
            let copy = s.batch.nodes.remove(&id);
            let remaining = s.batch.created_nodes.len();
            release_created_charge(s, batch_created, copy, |node| {
                crate::workspace::created_node_remove_delta(remaining, node)
            });
        }
        EntityId::Rel(id) => {
            let batch_created = s.batch.created_rels.remove(&id);
            let copy = s.batch.rels.remove(&id);
            let remaining = s.batch.created_rels.len();
            release_created_charge(s, batch_created, copy, |rel| {
                crate::workspace::created_rel_remove_delta(remaining, rel)
            });
        }
    }
}

/// The shared tail of [`release_created`]: a copy this batch created is
/// charged with its own bytes plus one created-set slot, so its delete
/// releases exactly that, priced against the set's post-removal size. A
/// copy this batch did not create (a copy-on-write copy of a pre-existing
/// entity) releases nothing. A created entity's copy is asserted live in
/// every configuration, accounting off included; the priced release
/// itself runs only while the workspace ledger is on.
fn release_created_charge<T>(
    s: &mut WriteScratch,
    batch_created: bool,
    copy: Option<T>,
    delta: impl FnOnce(&T) -> u64,
) {
    if !batch_created {
        return;
    }
    let copy = copy.expect("a batch-created entity's copy is live in the scratch");
    if !relate_core::tokens::workspace_accounting() {
        return;
    }
    s.shift_workspace(delta(&copy), 0);
}

/// The redo-op payload of one set_property, before the node/rel verb wraps
/// it into its [`RedoOp`] variant.
enum PropOpKind {
    Set(String, Value),
    Remove(String),
}

/// What one set_property did: the stats deltas plus the redo-op payload.
#[derive(Default)]
struct PropWrite {
    set: i64,
    removed: i64,
    op: Option<PropOpKind>,
}

/// The shared core of `set_property_node`/`set_property_rel`: apply the
/// null-means-remove / otherwise-upsert contract to one properties map and
/// report the stats deltas plus the redo-op payload. A null value removing
/// an absent key is a no-op (no deltas, no op).
fn set_prop_core(
    props: &mut relate_core::PropertyMap,
    created: bool,
    key: &str,
    value: &Value,
) -> PropWrite {
    if value.is_null() {
        if props.remove(key).is_some() {
            return PropWrite {
                set: 0,
                removed: 1,
                op: Some(PropOpKind::Remove(key.to_string())),
            };
        }
        return PropWrite::default();
    }
    let existed = props.contains_key(key);
    props.insert(key.to_string(), value.clone());
    let (set, removed) = prop_stat_deltas(existed, created);
    PropWrite {
        set,
        removed,
        op: Some(PropOpKind::Set(key.to_string(), value.clone())),
    }
}

/// The shared core of `replace_properties_*`: null out every current key the
/// map does not name, then set every entry, all through the one setter.
fn replace_props(
    keys: Vec<String>,
    map: BTreeMap<String, Value>,
    mut set: impl FnMut(&str, Value),
) {
    for k in &keys {
        if !map.contains_key(k) {
            set(k, Value::Null);
        }
    }
    for (k, v) in map {
        set(&k, v);
    }
}

/// Stats deltas for a set_property on a pre-existing (or CREATE-added) map:
/// overwriting an existing key counts set+removed; a fresh key counts set;
/// CREATE already counting the key (`created` on an `existed` map cell) is
/// the no-op.
fn prop_stat_deltas(existed: bool, created: bool) -> (i64, i64) {
    if existed && !created {
        (1, 1)
    } else if !existed {
        (1, 0)
    } else {
        (0, 0)
    }
}