Skip to main content

relate_executor/graph/
accounting.rs

1//! The graph's logical-byte accounting (ADR-0042, ADR-0202): the
2//! live-size oracle, the redo-batch admission estimates, and the charge
3//! helpers every mutation seam rides. Split out of `graph/mod.rs` (LABS-677).
4
5use std::collections::HashMap;
6use std::sync::Arc;
7
8use relate_core::{Node, NodeId, RelId};
9
10use super::*;
11
12impl Graph {
13    /// Live graph + index logical bytes (ADR-0042, ADR-0202).
14    pub fn used_bytes(&self) -> u64 {
15        self.used_bytes
16            .load(Ordering::Relaxed)
17            .saturating_add(self.interner.bytes())
18    }
19
20    /// Full walk of retained versions, adjacency, and the interner
21    /// (test / `rebuild_indexes` oracle).
22    pub fn accounted_bytes(&self) -> u64 {
23        self.structure_bytes().saturating_add(self.interner.bytes())
24    }
25
26    pub(super) fn structure_bytes(&self) -> u64 {
27        let charge = self.index_charge();
28        let mut n = 0u64;
29        n = n.saturating_add(self.nodes.array_bytes());
30        self.nodes.for_each(|_id, vers| {
31            n = n.saturating_add(crate::memory::node_chain_bytes(vers.shape()));
32            for v in vers.iter() {
33                n = n.saturating_add(crate::memory::live_node_account_live(
34                    v.live,
35                    &self.interner,
36                    &charge,
37                ));
38            }
39        });
40        n = n.saturating_add(self.rels.array_bytes());
41        self.rels.for_each(|_id, vers| {
42            n = n.saturating_add(crate::memory::rel_chain_bytes(vers.shape()));
43            for v in vers.iter() {
44                n = n.saturating_add(crate::memory::live_rel_account_live(v.live));
45            }
46        });
47        n = n.saturating_add(self.out_adj.array_bytes());
48        n = n.saturating_add(self.in_adj.array_bytes());
49        self.out_adj
50            .for_each(|_id, adj| n = n.saturating_add(adj.floor_bytes()));
51        self.in_adj
52            .for_each(|_id, adj| n = n.saturating_add(adj.floor_bytes()));
53        // The sealed side tables (ADR-0551) are retained structure: each
54        // entry's compressed chunks and tombstones, the floor ADR-0551
55        // prices, plus the slot arrays that hold them — the term the heap
56        // census reads as `slot_bytes`.
57        n = n.saturating_add(self.sealed_out.array_bytes());
58        n = n.saturating_add(self.sealed_in.array_bytes());
59        for sealed in [&self.sealed_out, &self.sealed_in] {
60            sealed.for_each(|_id, region| n = n.saturating_add(region.floor_bytes()));
61        }
62        // LABS-351 / LABS-370: the degree histograms and the count
63        // bundle's charged maps are retained structure — the recount
64        // oracle must include them or the incremental entry charges
65        // drift from it (the #398 lesson). Each family's term lives
66        // with the family (graph/degree_stats.rs,
67        // graph/count_state.rs) and composes here, at the oracle's
68        // one site, beside the constraint-key term.
69        n = n.saturating_add(self.degree_stats_structure_bytes());
70        n = n.saturating_add(self.count_state_structure_bytes());
71        // ADR-0439: the committed constraint-key map is retained structure
72        // too; it carries the bytes each entry was charged, so the recount
73        // and the incremental charge cannot drift.
74        n = n.saturating_add(self.constraint_keys_structure_bytes());
75        n
76    }
77
78    pub fn recompute_used(&self) {
79        self.used_bytes
80            .store(self.structure_bytes(), Ordering::Relaxed);
81    }
82
83    /// Live-size delta of `ops`. Nodes are accounted under the charge in
84    /// force after `ops`; when that differs from the current charge (DDL in
85    /// the batch), every retained version — including ones `ops` tombstone —
86    /// is moved from the old charge to the new one. A delete keeps its
87    /// record until GC, so it adds nothing. A copy-on-write set adds the
88    /// new version.
89    pub fn estimate_redo_delta(&self, ops: &[RedoOp]) -> i64 {
90        self.estimate_redo_delta_with_constraint_growth(ops, None)
91            .total
92    }
93
94    /// [`Graph::estimate_redo_delta`] with the constraint-key entry-growth
95    /// term optionally supplied by the caller. The group-commit admission
96    /// loop classifies each slot once and passes the delta its walk produced,
97    /// so the slot's ops are not re-classified here (ADR-0439).
98    #[doc(hidden)]
99    pub fn estimate_redo_delta_with_constraint_growth(
100        &self,
101        ops: &[RedoOp],
102        constraint_growth: Option<i64>,
103    ) -> crate::memory::RedoDelta {
104        let before = self.index_charge();
105        let after = self.charge_after_ops(ops);
106        let crate::memory::RedoDelta {
107            total: mut delta,
108            mut spill,
109        } = crate::memory::estimate_redo_delta(
110            &self.interner,
111            ops,
112            |id| self.node(id),
113            |id| self.rel_form(id),
114            |id| self.node_chain_shape(id),
115            |id| self.rel_chain_shape(id),
116            self.nodes.span(),
117            self.rels.span(),
118            &after,
119        );
120        let (adj_refusable, adj_spill) = self.estimate_adj_delta(ops);
121        delta += adj_refusable + adj_spill;
122        spill += adj_spill;
123        delta += self.estimate_intern_delta(ops);
124        // LABS-370 (security follow-up): the count family's entry growth
125        // is committed structure too — an oversized-label write must be
126        // rejected at admission, not after its entries land past the cap
127        // (graph/degree_stats.rs owns the term).
128        delta += self.estimate_stats_entry_growth(ops);
129        // ADR-0439: a constrained write's new entries are committed
130        // structure too — refused at admission, never after they land. The
131        // group path supplies the delta its admission walk already computed.
132        delta += match constraint_growth {
133            Some(growth) => growth,
134            None => self.estimate_constraint_key_entry_growth(ops),
135        };
136        if before.as_ref() != &after {
137            self.nodes.for_each(|id, vers| {
138                for v in vers.iter() {
139                    let n = v.live.to_node(id, &self.interner);
140                    delta += crate::memory::live_node_account(&n, &after) as i64
141                        - crate::memory::live_node_account(&n, &before) as i64;
142                }
143            });
144        }
145        crate::memory::RedoDelta {
146            total: delta,
147            spill,
148        }
149    }
150
151    /// The adjacency share of a batch's live-size delta, split into the
152    /// refusable growth — a create's hop and slot growth (dense span or the
153    /// side-map entry a wide id takes, as the store's own estimator charges
154    /// it), plus a founding delete's dense side-table span — and the spill
155    /// the checkpoint fold reclaims: a delete's region, chunk, and tombstone
156    /// terms, and the side-map entry a founding delete at a wide id takes
157    /// (ADR-0529).
158    pub(super) fn estimate_adj_delta(&self, ops: &[RedoOp]) -> (i64, i64) {
159        let mut out: HashMap<NodeId, Vec<(u32, usize)>> = HashMap::new();
160        let mut inn: HashMap<NodeId, Vec<(u32, usize)>> = HashMap::new();
161        let mut fresh_ids = FreshIds::new();
162        let mut delta = 0i64;
163        let slot = adj_slot();
164        let overflow = crate::memory::overflow_entry_bytes(adj_value());
165        let mut out_span = self.out_adj.span();
166        let mut in_span = self.in_adj.span();
167        let mut out_side = HashSet::new();
168        let mut in_side = HashSet::new();
169        // One traversal carries both halves: the create terms, and the
170        // batch's own rel identities and pending delete tombstones the
171        // delete half prices. A rel created earlier in this batch is
172        // invisible to the committed store, so its delete resolves from
173        // `created` — only creates already walked are in it, so a delete
174        // that precedes its create tombstones nothing, as in the apply path;
175        // a rel the store holds comes from its live version.
176        let mut created: HashMap<RelId, (NodeId, NodeId, u32)> = HashMap::new();
177        let mut pending_out: HashMap<NodeId, HashMap<u32, HashSet<RelId>>> = HashMap::new();
178        let mut pending_in: HashMap<NodeId, HashMap<u32, HashSet<RelId>>> = HashMap::new();
179        for op in ops {
180            match op {
181                RedoOp::CreateRel {
182                    id,
183                    start,
184                    end,
185                    rel_type,
186                    ..
187                } => {
188                    let type_id = fresh_ids.resolve(self, rel_type);
189                    created.insert(*id, (*start, *end, type_id));
190                    // One op touches both sides by the same rule, so each
191                    // side's store, sealed region, span, side-map set and
192                    // pending map travel together as one named value and
193                    // the loop runs once per endpoint — the pair the
194                    // incident and detach walks already iterate as a
195                    // slice. The fields name the side's slots because the
196                    // two store refs and the three mutable slots have
197                    // pairwise-identical types: a tuple position could
198                    // swap an out/in pair silently, a field name cannot.
199                    struct SideAdmission<'a, 'm> {
200                        adj: &'a IdVec<TypedAdj>,
201                        sealed: &'a IdVec<SealedAdj>,
202                        node: NodeId,
203                        span: &'m mut usize,
204                        side: &'m mut HashSet<NodeId>,
205                        pending: &'m mut HashMap<NodeId, Vec<(u32, usize)>>,
206                    }
207                    let mut sides = [
208                        SideAdmission {
209                            adj: &self.out_adj,
210                            sealed: &self.sealed_out,
211                            node: *start,
212                            span: &mut out_span,
213                            side: &mut out_side,
214                            pending: &mut out,
215                        },
216                        SideAdmission {
217                            adj: &self.in_adj,
218                            sealed: &self.sealed_in,
219                            node: *end,
220                            span: &mut in_span,
221                            side: &mut in_side,
222                            pending: &mut inn,
223                        },
224                    ];
225                    for side in &mut sides {
226                        if !side.adj.contains_key(&side.node) {
227                            // The one placement policy, priced here: a dense
228                            // growth is committed structure (refusable); a
229                            // side-map entry is priced once per node per
230                            // batch — this loop can revisit a node across
231                            // its ops, so the dedupe is this caller's.
232                            match crate::memory::place_in_span(side.span, side.node, slot) {
233                                // An id the array cannot index is refused by
234                                // the commit's own validation before anything
235                                // applies, so it prices nothing.
236                                None | Some(crate::memory::SpanPlacement::Inside) => {}
237                                Some(crate::memory::SpanPlacement::Grew(bytes)) => {
238                                    delta += bytes as i64;
239                                }
240                                Some(crate::memory::SpanPlacement::SideEntry) => {
241                                    if side.side.insert(side.node) {
242                                        delta += overflow as i64;
243                                    }
244                                }
245                            }
246                        }
247                        delta += bump_adj(side.pending, side.node, type_id, || {
248                            hop_counts(side.adj, side.sealed, side.node)
249                        });
250                    }
251                }
252                RedoOp::DeleteRel { id } => {
253                    let Some((start, end, type_id)) = created
254                        .get(id)
255                        .copied()
256                        // The store's rels answer through the one live-identity
257                        // spelling (a dead version's delete tombstones nothing,
258                        // as in the apply path).
259                        .or_else(|| self.rel_live_identity(*id))
260                    else {
261                        continue;
262                    };
263                    pending_out
264                        .entry(start)
265                        .or_default()
266                        .entry(type_id)
267                        .or_default()
268                        .insert(*id);
269                    pending_in
270                        .entry(end)
271                        .or_default()
272                        .entry(type_id)
273                        .or_default()
274                        .insert(*id);
275                }
276                _ => {}
277            }
278        }
279        // Each delete records one tombstone per endpoint that does not hold
280        // one yet (ADR-0551); the region, chunk, and tombstone terms are
281        // reclaimed at the checkpoint fold, so they are spill and never
282        // refuse a batch (ADR-0529: a delete at the cap commits). The
283        // founding side-table slot is the exception — the dense span only
284        // grows (ADR-0086) — so it stays refusable.
285        let (slot_growth, delete_spill) = self.estimate_delete_spill(&pending_out, &pending_in);
286        (delta + slot_growth, delete_spill)
287    }
288
289    /// The batch's delete terms, as `(refusable, spill)`: every delete
290    /// records one tombstone per endpoint that does not hold one yet
291    /// (ADR-0551) — a sealed chunk grows its tombstone vec, a never-sealed
292    /// type adds its on-demand chunk to the endpoint's region, all reclaimed
293    /// at the next checkpoint fold and so spill that never refuses a batch
294    /// (ADR-0529) — while a founding delete's dense side-table span is
295    /// permanent (ADR-0086) and stays refusable; its side-map entry,
296    /// reclaimed with the region, is spill like the rest.
297    fn estimate_delete_spill(
298        &self,
299        pending_out: &HashMap<NodeId, HashMap<u32, HashSet<RelId>>>,
300        pending_in: &HashMap<NodeId, HashMap<u32, HashSet<RelId>>>,
301    ) -> (i64, i64) {
302        let sealed_slot = sealed_slot();
303        let sealed_overflow = crate::memory::overflow_entry_bytes(sealed_value());
304        let (out_refusable, out_spill) =
305            price_side(&self.sealed_out, pending_out, sealed_slot, sealed_overflow);
306        let (in_refusable, in_spill) =
307            price_side(&self.sealed_in, pending_in, sealed_slot, sealed_overflow);
308        (out_refusable + in_refusable, out_spill + in_spill)
309    }
310
311    fn estimate_intern_delta(&self, ops: &[RedoOp]) -> i64 {
312        let mut seen = HashSet::new();
313        let mut extra = 0i64;
314        let mut consider = |s: &str| {
315            if !seen.insert(s.to_string()) {
316                return;
317            }
318            if self.interner.get_id(s).is_none() {
319                extra += crate::memory::interned_string_bytes(s.len()) as i64;
320            }
321        };
322        for op in ops {
323            match op {
324                RedoOp::CreateNode {
325                    labels, properties, ..
326                } => {
327                    for label in labels.iter() {
328                        consider(label);
329                    }
330                    for key in properties.keys() {
331                        consider(key);
332                    }
333                }
334                RedoOp::CreateRel {
335                    rel_type,
336                    properties,
337                    ..
338                } => {
339                    consider(rel_type);
340                    for key in properties.keys() {
341                        consider(key);
342                    }
343                }
344                RedoOp::SetNodeProp { key, .. }
345                | RedoOp::RemoveNodeProp { key, .. }
346                | RedoOp::SetRelProp { key, .. }
347                | RedoOp::RemoveRelProp { key, .. } => consider(key),
348                RedoOp::AddLabels { labels, .. } | RedoOp::RemoveLabels { labels, .. } => {
349                    for label in labels {
350                        consider(label);
351                    }
352                }
353                _ => {}
354            }
355        }
356        extra
357    }
358
359    pub(super) fn index_charge(&self) -> Arc<crate::memory::IndexCharge> {
360        Arc::clone(&self.indexes.charge_cache.lock().unwrap())
361    }
362
363    pub(super) fn refresh_index_charge(&self) {
364        let charge = {
365            let theater = self.theater.lock().unwrap();
366            Arc::new(crate::memory::IndexCharge::from_details(
367                theater.index_details.values(),
368            ))
369        };
370        *self.indexes.charge_cache.lock().unwrap() = charge;
371    }
372
373    fn charge_after_ops(&self, ops: &[RedoOp]) -> crate::memory::IndexCharge {
374        let theater = self.theater.lock().unwrap();
375        let mut details = theater.index_details.clone();
376        drop(theater);
377        crate::redo::project_index_details(&mut details, ops);
378        crate::memory::IndexCharge::from_details(details.values())
379    }
380
381    pub(super) fn charge(&self, delta: i64) {
382        if delta > 0 {
383            self.used_bytes.fetch_add(delta as u64, Ordering::Relaxed);
384        } else if delta < 0 {
385            let sub = (-delta) as u64;
386            atomic_fetch_update!(self.used_bytes, Ordering::Relaxed, Ordering::Relaxed, |u| {
387                Some(u.saturating_sub(sub))
388            })
389            .expect("the saturating-sub closure never rejects");
390        }
391    }
392
393    pub(super) fn charge_node_swap(&self, before: Option<&Node>, after: Option<&Node>) {
394        let charge = self.index_charge();
395        let b = before
396            .map(|n| crate::memory::live_node_account(n, &charge))
397            .unwrap_or(0);
398        let a = after
399            .map(|n| crate::memory::live_node_account(n, &charge))
400            .unwrap_or(0);
401        self.charge(a as i64 - b as i64);
402    }
403
404    pub(super) fn charge_rel_after_edit(
405        &self,
406        id: RelId,
407        before_bytes: u64,
408        before_shape: ChainShape,
409    ) {
410        let after_shape = self.rel_chain_shape(id);
411        let after_bytes = self.visible_rel_account(id);
412        if after_shape != before_shape {
413            let growth = crate::memory::rel_chain_bytes(after_shape) as i64
414                - crate::memory::rel_chain_bytes(before_shape) as i64;
415            self.charge(after_bytes as i64 + growth);
416        } else {
417            self.charge(after_bytes as i64 - before_bytes as i64);
418        }
419    }
420
421    #[cfg(test)]
422    pub(super) fn node_chain_len(&self, id: NodeId) -> usize {
423        self.nodes.get(&id).map_or(0, |v| v.len())
424    }
425
426    pub(super) fn node_chain_shape(&self, id: NodeId) -> ChainShape {
427        self.nodes
428            .get(&id)
429            .map_or(ChainShape::Absent, |v| v.shape())
430    }
431
432    pub(super) fn rel_chain_shape(&self, id: RelId) -> ChainShape {
433        self.rels.get(&id).map_or(ChainShape::Absent, |v| v.shape())
434    }
435
436    /// Copy-on-write keeps the previous version. An in-place edit replaces it.
437    pub(super) fn charge_node_after_edit(
438        &self,
439        id: NodeId,
440        before: Option<&Node>,
441        before_shape: ChainShape,
442    ) {
443        let after = self.node(id);
444        let after_shape = self.node_chain_shape(id);
445        if after_shape != before_shape {
446            let charge = self.index_charge();
447            let added = after
448                .as_ref()
449                .map(|n| crate::memory::live_node_account(n, &charge))
450                .unwrap_or(0);
451            let growth = crate::memory::node_chain_bytes(after_shape) as i64
452                - crate::memory::node_chain_bytes(before_shape) as i64;
453            self.charge(added as i64 + growth);
454        } else {
455            self.charge_node_swap(before, after.as_ref());
456        }
457    }
458}
459
460pub(super) fn hop_counts(
461    map: &IdVec<TypedAdj>,
462    sealed: &IdVec<SealedAdj>,
463    node: NodeId,
464) -> Vec<(u32, usize)> {
465    map.get(&node)
466        .map(|adj| {
467            adj.chunk_lens(sealed.get(&node).as_deref())
468                .map(|(type_id, delta, sealed)| (type_id, delta + sealed))
469                .collect()
470        })
471        .unwrap_or_default()
472}
473
474/// The admission estimates' fresh-name resolver (LABS-425, stellar round
475/// 1): a name the interner does not know — a label or rel type the
476/// not-yet-applied batch mints — resolves to a descending id below the
477/// committed range, one id per distinct name. Both estimate terms
478/// ([`Graph::estimate_adj_delta`] here,
479/// [`Graph::estimate_stats_entry_growth`] in
480/// graph/degree_stats_estimate.rs) resolved this ladder by hand before;
481/// the descending-id collision invariant (fresh ids never collide with
482/// committed ids or each other) now lives in exactly one place.
483#[derive(Clone, Debug, PartialEq)]
484pub(super) struct FreshIds {
485    fresh: HashMap<String, u32>,
486    next: u32,
487}
488
489impl FreshIds {
490    pub(super) fn new() -> Self {
491        Self {
492            fresh: HashMap::new(),
493            next: u32::MAX,
494        }
495    }
496
497    /// The interned id, else this batch's earlier mint, else a new
498    /// descending id minted and memoized.
499    pub(super) fn resolve(&mut self, g: &Graph, name: &str) -> u32 {
500        g.interner
501            .get_id(name)
502            .or_else(|| self.fresh.get(name).copied())
503            .unwrap_or_else(|| {
504                let id = self.next;
505                self.next = self.next.saturating_sub(1);
506                self.fresh.insert(name.to_string(), id);
507                id
508            })
509    }
510}
511
512/// One node's adjacency floor in one direction: the delta hop bytes plus its
513/// sealed side-table entry's compressed chunks and tombstones.
514pub(super) fn adj_floor(map: &IdVec<TypedAdj>, sealed: &IdVec<SealedAdj>, node: NodeId) -> u64 {
515    map.get(&node).map(|adj| adj.floor_bytes()).unwrap_or(0)
516        + sealed.get(&node).map_or(0, |region| region.floor_bytes())
517}
518
519/// One side's share of the delete terms
520/// ([`Graph::estimate_delete_spill`](Graph::estimate_delete_spill)'s phase
521/// 2), as the `(refusable, spill)` pair: per node, the region-level terms —
522/// the node's dense slot span (permanent, refusable) or its reclaimed
523/// side-map entry (spill), and the chunks-vec entry growth across every
524/// joining type, one
525/// before-and-after term per region, never one per type, or the reserved
526/// model's pow2 steps misprice a batch that joins several — then each key's
527/// own terms (all fold-reclaimed, spill): a sealed chunk's tombstone-vec
528/// growth, or a joining chunk's empty stream and tombstones.
529fn price_side(
530    sealed: &IdVec<SealedAdj>,
531    pending: &HashMap<NodeId, HashMap<u32, HashSet<RelId>>>,
532    sealed_slot: u64,
533    sealed_overflow: u64,
534) -> (i64, i64) {
535    let mut span = sealed.span();
536    let mut refusable = 0i64;
537    let mut spill = 0i64;
538    for (node, keys) in pending {
539        // One key loop prices every key's own term: a chunk the region
540        // already holds grows its tombstone vec (a delete after a
541        // reposition updates the existing slot in place), a type the
542        // region does not hold joins it, bringing the empty stream and
543        // its tombstones — priced once, here, never again in a
544        // region-level arm.
545        let region = sealed.get(node);
546        let mut joining = 0;
547        for (type_id, ids) in keys {
548            match region.as_ref().and_then(|region| region.chunk(*type_id)) {
549                Some(chunk) => {
550                    let fresh = chunk.fresh_tombstone_count(ids);
551                    spill += chunk.tombstone_growth_bytes(fresh) as i64;
552                }
553                None => {
554                    joining += 1;
555                    spill += crate::adjacency::fresh_sealed_chunk_floor_bytes(ids.len()) as i64;
556                }
557            }
558        }
559        // The region-level term, once per node: a founding delete grows the
560        // node's slot in the side table — the dense span permanently
561        // (refusable), a wide id's side-map entry only until the region
562        // empties (spill) — and its chunks-vec entry growth is one
563        // before-and-after term over every joining type, never one per
564        // type, or the reserved model's pow2 steps misprice a batch that
565        // joins several. An existing region prices the same entry growth
566        // (zero when nothing joined).
567        match region {
568            None => {
569                // The one placement policy, priced here: a dense slot-span
570                // growth is permanent (refusable), a wide id's side-map
571                // entry is reclaimed with the region it founds (spill). Each
572                // node reaches this arm once (`pending` is keyed by node), so
573                // the entry prices unconditionally — the per-batch dedupe is
574                // the create loop's, where a node can recur.
575                match crate::memory::place_in_span(&mut span, *node, sealed_slot) {
576                    None | Some(crate::memory::SpanPlacement::Inside) => {}
577                    Some(crate::memory::SpanPlacement::Grew(bytes)) => refusable += bytes as i64,
578                    Some(crate::memory::SpanPlacement::SideEntry) => {
579                        spill += sealed_overflow as i64;
580                    }
581                }
582                spill += crate::adjacency::fresh_sealed_chunk_entry_bytes(joining) as i64;
583            }
584            Some(region) => {
585                spill += region.chunk_entry_growth_bytes(joining) as i64;
586            }
587        }
588    }
589    (refusable, spill)
590}
591
592fn bump_adj(
593    sim: &mut HashMap<NodeId, Vec<(u32, usize)>>,
594    node: NodeId,
595    type_id: u32,
596    init: impl FnOnce() -> Vec<(u32, usize)>,
597) -> i64 {
598    let chunks = sim.entry(node).or_insert_with(init);
599    let before =
600        crate::memory::adjacency_bytes(&chunks.iter().map(|(_, n)| *n).collect::<Vec<_>>());
601    if let Some(slot) = chunks.iter_mut().find(|c| c.0 == type_id) {
602        slot.1 += 1;
603    } else {
604        chunks.push((type_id, 1));
605    }
606    let after = crate::memory::adjacency_bytes(&chunks.iter().map(|(_, n)| *n).collect::<Vec<_>>());
607    after as i64 - before as i64
608}