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::{EntityId, 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.batch.bump_live_labels(&labels, 1);
51        s.push_redo(RedoOp::CreateNode {
52            id,
53            labels,
54            properties,
55        });
56        drop(s);
57        relate_core::tokens::poll()?;
58        Ok(id)
59    }
60
61    pub fn create_rel(
62        &self,
63        start: NodeId,
64        end: NodeId,
65        rel_type: String,
66        properties: BTreeMap<String, Value>,
67    ) -> Result<RelId> {
68        if !self.node_exists(start) || !self.node_exists(end) {
69            return Err(crate::graph::missing_rel_endpoint_error());
70        }
71        let properties = std::sync::Arc::new(relate_core::PropertyMap::from(properties));
72        let mut s = self.scratch_mut();
73        s.reserve_new_rel(&Relationship {
74            id: 0,
75            start,
76            end,
77            rel_type: rel_type.clone(),
78            properties: std::sync::Arc::clone(&properties),
79        })?;
80        let id = s.alloc_rel()?;
81        s.statement.stats.relationships_created += 1;
82        s.statement.stats.properties_set += properties.len() as i64;
83        s.batch.rels.insert(
84            id,
85            Relationship {
86                id,
87                start,
88                end,
89                rel_type: rel_type.clone(),
90                properties: std::sync::Arc::clone(&properties),
91            },
92        );
93        s.batch.out_adj.entry(start).or_default().push(id);
94        s.batch.in_adj.entry(end).or_default().push(id);
95        s.push_redo(RedoOp::CreateRel {
96            id,
97            start,
98            end,
99            rel_type,
100            properties,
101        });
102        drop(s);
103        relate_core::tokens::poll()?;
104        Ok(id)
105    }
106
107    fn cow_node<'b>(s: &'b mut WriteScratch, base: &Graph, id: NodeId) -> Option<&'b mut Node> {
108        if s.batch.deleted_nodes.contains(&id) {
109            return None;
110        }
111        if !s.batch.nodes.contains_key(&id) {
112            let n = base.node_at(id, s.snapshot_ts())?;
113            // LABS-1085 review: a copy-on-write introduces the base node
114            // into the scratch, so its whole label/property vocabulary
115            // posts into the equality index — exactly what a create
116            // posts. Without this, a pair built before the cow misses
117            // the node's pre-existing properties, and a keyed lookup
118            // (MERGE's match arm) silently misses the node and creates
119            // a duplicate. Set/label ops on the copy post on top;
120            // postings are sets, so a double post is harmless.
121            for (key, value) in &*n.properties {
122                s.batch.prop_ix.post_value(id, &n.labels, key, value);
123            }
124            s.batch.nodes.insert(id, n);
125        }
126        s.batch.nodes.get_mut(&id)
127    }
128
129    fn cow_rel<'b>(
130        s: &'b mut WriteScratch,
131        base: &Graph,
132        id: RelId,
133    ) -> Option<&'b mut Relationship> {
134        if s.batch.deleted_rels.contains(&id) {
135            return None;
136        }
137        if !s.batch.rels.contains_key(&id) {
138            let r = base.rel_at(id, s.snapshot_ts())?;
139            // The node cow's posting contract (above), on the rel index.
140            for (key, value) in &*r.properties {
141                s.batch.rel_prop_ix.post_value(id, &r.rel_type, key, value);
142            }
143            s.batch.rels.insert(id, r);
144        }
145        s.batch.rels.get_mut(&id)
146    }
147
148    pub fn add_labels(&self, id: NodeId, labels: &[String]) {
149        if labels.is_empty() {
150            return;
151        }
152        let existing = self.node_labels(id).unwrap_or_default();
153        // The labels this write actually adds: the distinct requested labels
154        // not already on the node, in first-occurrence order. Computed once
155        // and reused for the accounting and the cow block; `n.labels ==
156        // existing` at cow time, so the cow block pushes `fresh` as-is
157        // instead of re-answering the membership question per label.
158        let fresh: Vec<String> = distinct_labels(labels)
159            .into_iter()
160            .filter(|l| !existing.iter().any(|x| x == *l))
161            .map(str::to_string)
162            .collect();
163        let mut s = self.scratch_mut();
164        let (labels_added, labels_removed) = self.label_deltas(&s, &fresh, LabelChange::Gain);
165        let created = s.batch.created_nodes.contains(&id);
166        let shift = CreatedShift::begin(&s, created, node_label_bytes(id));
167        let mut added = Vec::new();
168        if let Some(n) = Self::cow_node(&mut s, self.base, id) {
169            std::sync::Arc::make_mut(&mut n.labels).extend(fresh.iter().cloned());
170            added = fresh;
171        }
172        shift.finish(&mut s);
173        s.net_label_stats(labels_added, labels_removed);
174        if !added.is_empty() {
175            s.batch.bump_live_labels(&added, 1);
176            s.push_redo(RedoOp::add_labels(id, added));
177        }
178    }
179
180    pub fn remove_labels(&self, id: NodeId, labels: &[String]) {
181        // Cow the node first and derive everything from `n.labels` in one
182        // pass: `extract_if` walks the node's labels once, dropping the
183        // ones the request names and collecting them into `actually` in
184        // node order. `requested` answers membership in O(1) per node
185        // label; `actually` feeds the accounting and the live-label bump
186        // (both consumers dedupe, so node order is as good as request
187        // order). A missing or scratch-deleted node leaves `actually`
188        // empty, exactly what the pre-cow read answered for it.
189        let requested: HashSet<&str> = labels.iter().map(String::as_str).collect();
190        let mut s = self.scratch_mut();
191        let created = s.batch.created_nodes.contains(&id);
192        let shift = CreatedShift::begin(&s, created, node_label_bytes(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.finish(&mut s);
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.batch.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 shift = CreatedShift::begin(&s, created, node_property_bytes(id));
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.finish(&mut s);
244        finish_set_property(&mut s, outcome, |op| match op {
245            PropOpKind::Set(k, v) => RedoOp::set_node_prop(id, k, v),
246            PropOpKind::Remove(k) => RedoOp::remove_node_prop(id, k),
247        });
248    }
249
250    pub fn set_property_rel(&self, id: RelId, key: &str, value: Value) {
251        let mut s = self.scratch_mut();
252        let created = s.batch.created_rels.contains(&id);
253        let shift = CreatedShift::begin(&s, created, rel_property_bytes(id));
254        let outcome = Self::cow_rel(&mut s, self.base, id).map(|r| {
255            set_prop_core(
256                std::sync::Arc::make_mut(&mut r.properties),
257                created,
258                key,
259                &value,
260            )
261        });
262        shift.finish(&mut s);
263        finish_set_property(&mut s, outcome, |op| match op {
264            PropOpKind::Set(k, v) => RedoOp::set_rel_prop(id, k, v),
265            PropOpKind::Remove(k) => RedoOp::remove_rel_prop(id, k),
266        });
267    }
268
269    /// `SET n += map`: per-key merge through the set verb (an existing
270    /// key keeps its position, a new one is added) — the node and
271    /// relationship forms are the same loop over their set verbs.
272    pub fn merge_properties_node(&self, id: NodeId, map: &BTreeMap<String, Value>) {
273        for (k, v) in map {
274            self.set_property_node(id, k, v.clone());
275        }
276    }
277
278    /// The relationship form of [`Self::merge_properties_node`].
279    pub fn merge_properties_rel(&self, id: RelId, map: &BTreeMap<String, Value>) {
280        for (k, v) in map {
281            self.set_property_rel(id, k, v.clone());
282        }
283    }
284
285    pub fn replace_properties_node(&self, id: NodeId, map: BTreeMap<String, Value>) {
286        let keys: Vec<String> = self
287            .node(id)
288            .map(|n| n.properties.keys().cloned().collect())
289            .unwrap_or_default();
290        replace_props(keys, map, |k, v| self.set_property_node(id, k, v));
291    }
292
293    pub fn replace_properties_rel(&self, id: RelId, map: BTreeMap<String, Value>) {
294        let keys: Vec<String> = self
295            .rel(id)
296            .map(|r| r.properties.keys().cloned().collect())
297            .unwrap_or_default();
298        replace_props(keys, map, |k, v| self.set_property_rel(id, k, v));
299    }
300
301    /// The kind-addressed forms of the three property verbs a resolved
302    /// write drives: the `EntityId` selector lives here once, so no write
303    /// arm re-opens a `match entity { Node => …_node, Rel => …_rel }` of
304    /// its own.
305    pub(crate) fn set_property(&self, entity: EntityId, key: &str, value: Value) {
306        match entity {
307            EntityId::Node(id) => self.set_property_node(id, key, value),
308            EntityId::Rel(id) => self.set_property_rel(id, key, value),
309        }
310    }
311
312    /// [`Self::set_property`]'s full-replacement form.
313    pub(crate) fn replace_properties(&self, entity: EntityId, map: BTreeMap<String, Value>) {
314        match entity {
315            EntityId::Node(id) => self.replace_properties_node(id, map),
316            EntityId::Rel(id) => self.replace_properties_rel(id, map),
317        }
318    }
319
320    /// [`Self::set_property`]'s per-key merge form.
321    pub(crate) fn merge_properties(&self, entity: EntityId, map: &BTreeMap<String, Value>) {
322        match entity {
323            EntityId::Node(id) => self.merge_properties_node(id, map),
324            EntityId::Rel(id) => self.merge_properties_rel(id, map),
325        }
326    }
327
328    pub fn delete_rel(&self, id: RelId) {
329        // One fetch answers both "is the rel live" and "what it carries":
330        // a missing rel has nothing to delete (the `let … else` twin of
331        // `delete_node`'s form).
332        let Some(r) = self.rel(id) else { return };
333        let nprops = r.properties.len() as i64;
334        let mut s = self.scratch_mut();
335        release_created(&mut s, EntityId::Rel(id));
336        s.batch.deleted_rels.insert(id);
337        net_or_count_delete(&mut s, EntityId::Rel(id), nprops);
338        s.push_redo(RedoOp::delete_rel(id));
339    }
340
341    pub fn delete_node(&self, id: NodeId, detach: bool) -> Result<()> {
342        let incident: Vec<RelId> = self.neighbors(id, Direction::Both);
343        if !detach && !incident.is_empty() {
344            return Err(crate::graph::delete_connected_node_error());
345        }
346        for rid in &incident {
347            self.delete_rel(*rid);
348        }
349        // One fetch answers both "is the node live" and "what does it
350        // carry": a missing node has nothing to delete.
351        let Some(node) = self.node(id) else {
352            return Ok(());
353        };
354        let nprops = node.properties.len() as i64;
355        let labels = node.labels;
356        let mut s = self.scratch_mut();
357        let (labels_added, labels_removed) = self.label_deltas(&s, &labels, LabelChange::Loss);
358        release_created(&mut s, EntityId::Node(id));
359        s.batch.deleted_nodes.insert(id);
360        s.batch.bump_live_labels(&labels, -1);
361        s.net_label_stats(labels_added, labels_removed);
362        net_or_count_delete(&mut s, EntityId::Node(id), nprops);
363        s.push_redo(RedoOp::delete_node(id));
364        Ok(())
365    }
366}
367
368/// The per-kind state one delete nets against (REL8-1188): the statement-local
369/// created set's verdict plus the four counter targets the decision writes.
370/// One bundle per kind, so the node/rel vocabulary is dispatched exactly once.
371struct DeleteNets<'a> {
372    statement_created: bool,
373    created: &'a mut i64,
374    set: &'a mut i64,
375    deleted: &'a mut i64,
376    removed: &'a mut i64,
377}
378
379/// The net-or-count decision both delete verbs share (REL8-1188). A delete
380/// nets the create's counters only for an entity *this statement* created in
381/// the batch it is deleting in — the id is still in the statement-local
382/// created set, which a batch rebase clears together with the batch's own
383/// charged created set ([`WriteScratch::rebase`]) — so a create/delete pair
384/// inside one statement cancels (the pinned
385/// `create_then_delete_cancels_create_stats` model). Every other delete
386/// counts as this statement's delete: of a pre-existing entity, of one an
387/// earlier statement of the transaction created (the create was counted by
388/// that statement, so netting here would drive the counter negative and
389/// poison every binding through the wire-stats boundary), or of one an
390/// earlier batch of this batched statement already committed
391/// (`CALL { … } IN TRANSACTIONS`, ADR-0210 — the committed create and the
392/// delete both report).
393fn net_or_count_delete(s: &mut WriteScratch, entity: EntityId, nprops: i64) {
394    let nets = match entity {
395        EntityId::Node(id) => DeleteNets {
396            statement_created: s.statement.created_nodes.remove(&id),
397            created: &mut s.statement.stats.nodes_created,
398            set: &mut s.statement.stats.properties_set,
399            deleted: &mut s.statement.stats.nodes_deleted,
400            removed: &mut s.statement.stats.properties_removed,
401        },
402        EntityId::Rel(id) => DeleteNets {
403            statement_created: s.statement.created_rels.remove(&id),
404            created: &mut s.statement.stats.relationships_created,
405            set: &mut s.statement.stats.properties_set,
406            deleted: &mut s.statement.stats.relationships_deleted,
407            removed: &mut s.statement.stats.properties_removed,
408        },
409    };
410    if nets.statement_created {
411        // The statement counted this create, so both counters still hold it:
412        // every property the entity carries was counted at the create or by a
413        // later write. `checked_sub` + the named expect keep a broken
414        // statement-created fact from the silent `saturating_sub` clamp that
415        // was the REL8-1188 bug; the i64 floor is refused here, and
416        // non-negativity is tripped where it is owned — the wire boundary's
417        // own expect (`relate::query_stats_to_wire`).
418        *nets.created = nets
419            .created
420            .checked_sub(1)
421            .expect("a statement-created entity's create counter still holds it");
422        *nets.set = nets
423            .set
424            .checked_sub(nprops)
425            .expect("a statement-created entity's property counter still holds it");
426    } else {
427        *nets.deleted += 1;
428        *nets.removed += nprops;
429    }
430}
431
432/// The workspace bytes the created node `id`'s labels hold now, `None`
433/// when the scratch has no copy of it.
434fn node_label_bytes(id: NodeId) -> impl Fn(&WriteScratch) -> Option<u64> {
435    move |s| {
436        s.batch
437            .nodes
438            .get(&id)
439            .map(|node| crate::workspace::created_label_bytes(&node.labels))
440    }
441}
442
443/// The workspace bytes the created node `id`'s properties hold now.
444fn node_property_bytes(id: NodeId) -> impl Fn(&WriteScratch) -> Option<u64> {
445    move |s| {
446        s.batch
447            .nodes
448            .get(&id)
449            .map(|node| crate::workspace::created_property_delta(&node.properties))
450    }
451}
452
453/// The workspace bytes the created relationship `id`'s properties hold now.
454fn rel_property_bytes(id: RelId) -> impl Fn(&WriteScratch) -> Option<u64> {
455    move |s| {
456        s.batch
457            .rels
458            .get(&id)
459            .map(|rel| crate::workspace::created_property_delta(&rel.properties))
460    }
461}
462
463/// The created-entity workspace shift as one guard: [`Self::begin`] snapshots
464/// the bytes `bytes` reads off the scratch copy (only when workspace
465/// accounting is on and the entity was created in this batch), and
466/// [`Self::finish`] re-reads them after the write and shifts the workspace
467/// by the difference. A snapshot exists only for an entity the scratch
468/// already held, and the cow never removes it.
469struct CreatedShift<F: Fn(&WriteScratch) -> Option<u64>> {
470    before: Option<u64>,
471    bytes: F,
472}
473
474impl<F: Fn(&WriteScratch) -> Option<u64>> CreatedShift<F> {
475    fn begin(s: &WriteScratch, created: bool, bytes: F) -> Self {
476        let before = if created && relate_core::tokens::workspace_accounting() {
477            bytes(s)
478        } else {
479            None
480        };
481        Self { before, bytes }
482    }
483
484    fn finish(self, s: &mut WriteScratch) {
485        let Some(before) = self.before else {
486            return;
487        };
488        let after = (self.bytes)(s).expect("the cow inserted the scratch copy");
489        s.shift_workspace(before, after);
490    }
491}
492
493/// The stats + redo tail `set_property_node`/`set_property_rel` share: fold
494/// the write's deltas into the statement stats and push the redo op the
495/// caller's constructor builds from the payload.
496fn finish_set_property(
497    s: &mut WriteScratch,
498    outcome: Option<PropWrite>,
499    redo: impl FnOnce(PropOpKind) -> RedoOp,
500) {
501    // A missing or scratch-deleted entity (no cow copy) is a no-op write.
502    let Some(PropWrite { set, removed, op }) = outcome else {
503        return;
504    };
505    s.statement.stats.properties_set += set;
506    s.statement.stats.properties_removed += removed;
507    if let Some(op) = op {
508        s.push_redo(redo(op));
509    }
510}
511
512/// The bookkeeping half of one delete, dispatched once per kind on
513/// [`EntityId`] (the same vocabulary [`net_or_count_delete`] reads): drop
514/// the entity's batch-set membership and take its scratch copy out — both
515/// unconditional, so the charged set never retains a deleted id — then
516/// release the copy's workspace charge when this batch created it. The
517/// write direction of the same charge is the `CreatedShift` pair beside
518/// this; a pre-existing entity's copy (a copy-on-write edit) was never
519/// charged as a create, so its delete releases nothing.
520fn release_created(s: &mut WriteScratch, entity: EntityId) {
521    match entity {
522        EntityId::Node(id) => {
523            let batch_created = s.batch.created_nodes.remove(&id);
524            let copy = s.batch.nodes.remove(&id);
525            let remaining = s.batch.created_nodes.len();
526            release_created_charge(s, batch_created, copy, |node| {
527                crate::workspace::created_node_remove_delta(remaining, node)
528            });
529        }
530        EntityId::Rel(id) => {
531            let batch_created = s.batch.created_rels.remove(&id);
532            let copy = s.batch.rels.remove(&id);
533            let remaining = s.batch.created_rels.len();
534            release_created_charge(s, batch_created, copy, |rel| {
535                crate::workspace::created_rel_remove_delta(remaining, rel)
536            });
537        }
538    }
539}
540
541/// The shared tail of [`release_created`]: a copy this batch created is
542/// charged with its own bytes plus one created-set slot, so its delete
543/// releases exactly that, priced against the set's post-removal size. A
544/// copy this batch did not create (a copy-on-write copy of a pre-existing
545/// entity) releases nothing. A created entity's copy is asserted live in
546/// every configuration, accounting off included; the priced release
547/// itself runs only while the workspace ledger is on.
548fn release_created_charge<T>(
549    s: &mut WriteScratch,
550    batch_created: bool,
551    copy: Option<T>,
552    delta: impl FnOnce(&T) -> u64,
553) {
554    if !batch_created {
555        return;
556    }
557    let copy = copy.expect("a batch-created entity's copy is live in the scratch");
558    if !relate_core::tokens::workspace_accounting() {
559        return;
560    }
561    s.shift_workspace(delta(&copy), 0);
562}
563
564/// The redo-op payload of one set_property, before the node/rel verb wraps
565/// it into its [`RedoOp`] variant.
566enum PropOpKind {
567    Set(String, Value),
568    Remove(String),
569}
570
571/// What one set_property did: the stats deltas plus the redo-op payload.
572#[derive(Default)]
573struct PropWrite {
574    set: i64,
575    removed: i64,
576    op: Option<PropOpKind>,
577}
578
579/// The shared core of `set_property_node`/`set_property_rel`: apply the
580/// null-means-remove / otherwise-upsert contract to one properties map and
581/// report the stats deltas plus the redo-op payload. A null value removing
582/// an absent key is a no-op (no deltas, no op).
583fn set_prop_core(
584    props: &mut relate_core::PropertyMap,
585    created: bool,
586    key: &str,
587    value: &Value,
588) -> PropWrite {
589    if value.is_null() {
590        if props.remove(key).is_some() {
591            return PropWrite {
592                set: 0,
593                removed: 1,
594                op: Some(PropOpKind::Remove(key.to_string())),
595            };
596        }
597        return PropWrite::default();
598    }
599    let existed = props.contains_key(key);
600    props.insert(key.to_string(), value.clone());
601    let (set, removed) = prop_stat_deltas(existed, created);
602    PropWrite {
603        set,
604        removed,
605        op: Some(PropOpKind::Set(key.to_string(), value.clone())),
606    }
607}
608
609/// The shared core of `replace_properties_*`: null out every current key the
610/// map does not name, then set every entry, all through the one setter.
611fn replace_props(
612    keys: Vec<String>,
613    map: BTreeMap<String, Value>,
614    mut set: impl FnMut(&str, Value),
615) {
616    for k in &keys {
617        if !map.contains_key(k) {
618            set(k, Value::Null);
619        }
620    }
621    for (k, v) in map {
622        set(&k, v);
623    }
624}
625
626/// Stats deltas for a set_property on a pre-existing (or CREATE-added) map:
627/// overwriting an existing key counts set+removed; a fresh key counts set;
628/// CREATE already counting the key (`created` on an `existed` map cell) is
629/// the no-op.
630fn prop_stat_deltas(existed: bool, created: bool) -> (i64, i64) {
631    if existed && !created {
632        (1, 1)
633    } else if !existed {
634        (1, 0)
635    } else {
636        (0, 0)
637    }
638}