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::sync::Arc;
6
7use relate_core::{Node, NodeId, RelId};
8
9use super::*;
10
11pub(super) mod adjacency;
12
13impl Graph {
14    /// Live graph + index logical bytes (ADR-0042, ADR-0202).
15    pub fn used_bytes(&self) -> u64 {
16        self.used_bytes
17            .load(Ordering::Relaxed)
18            .saturating_add(self.interner.bytes())
19    }
20
21    /// Full walk of retained versions, adjacency, and the interner
22    /// (test / `rebuild_indexes` oracle).
23    pub fn accounted_bytes(&self) -> u64 {
24        self.structure_bytes().saturating_add(self.interner.bytes())
25    }
26
27    pub(super) fn structure_bytes(&self) -> u64 {
28        let charge = self.index_charge();
29        let mut n = 0u64;
30        n = n.saturating_add(self.nodes.array_bytes());
31        self.nodes.for_each(|_id, vers| {
32            n = n.saturating_add(crate::memory::chain_bytes(
33                vers.shape(),
34                node_version_stride(),
35            ));
36            for v in vers.iter() {
37                n = n.saturating_add(crate::memory::live_node_account_live(
38                    v.live,
39                    &self.interner,
40                    &charge,
41                ));
42            }
43        });
44        n = n.saturating_add(self.rels.array_bytes());
45        self.rels.for_each(|_id, vers| {
46            n = n.saturating_add(crate::memory::chain_bytes(
47                vers.shape(),
48                rel_version_stride(),
49            ));
50            for v in vers.iter() {
51                n = n.saturating_add(crate::memory::live_rel_account_live(v.live));
52            }
53        });
54        // Each side's slot arrays and retained delta entries, and the sealed
55        // arenas (ADR-0551 / ADR-0599) — the arena bytes, the 12-byte
56        // entries, the tombstones, and the dense span tables that index
57        // them — the term the heap census reads as `slot_bytes`.
58        for side in [self.out_side(), self.in_side()] {
59            n = n.saturating_add(side.delta().array_bytes());
60            side.delta()
61                .for_each(|_id, adj| n = n.saturating_add(adj.floor_bytes()));
62        }
63        n = n.saturating_add(self.sealed_floor());
64        // LABS-351 / LABS-370: the degree histograms and the count
65        // bundle's charged maps are retained structure — the recount
66        // oracle must include them or the incremental entry charges
67        // drift from it (the #398 lesson). Each family's term lives
68        // with the family (graph/degree_stats.rs,
69        // graph/count_state.rs) and composes here, at the oracle's
70        // one site, beside the constraint-key term.
71        n = n.saturating_add(self.degree_stats_structure_bytes());
72        n = n.saturating_add(self.count_state_structure_bytes());
73        // ADR-0439: the committed constraint-key map is retained structure
74        // too; it carries the bytes each entry was charged, so the recount
75        // and the incremental charge cannot drift.
76        n = n.saturating_add(self.constraint_keys_structure_bytes());
77        n
78    }
79
80    pub fn recompute_used(&self) {
81        self.used_bytes
82            .store(self.structure_bytes(), Ordering::Relaxed);
83    }
84
85    /// The committed dense id spans — a group admission walk's seed
86    /// ([`DenseSpans`](crate::memory::DenseSpans)): its first slot
87    /// estimates against these and the walk carries the values each
88    /// admitted slot advanced them to. Every dense span the admission
89    /// estimate prices rides here: the node and relationship slot arrays,
90    /// the adjacency tier's two directions, and the sealed span table's
91    /// two.
92    #[doc(hidden)]
93    pub fn dense_spans(&self) -> crate::memory::DenseSpans {
94        crate::memory::DenseSpans {
95            node: self.nodes.span(),
96            rel: self.rels.span(),
97            adj_out: self.out_side().delta().span(),
98            adj_in: self.in_side().delta().span(),
99            sealed_out: self.out_side().sealed().span(),
100            sealed_in: self.in_side().sealed().span(),
101        }
102    }
103
104    /// Live-size delta of `ops`, its spill reported separately
105    /// ([`RedoDelta::spill`](crate::memory::RedoDelta::spill)). Nodes are
106    /// accounted under the charge in force after `ops`; when that differs
107    /// from the current charge (DDL in the batch), every retained version —
108    /// including ones `ops` tombstone — is moved from the old charge to the
109    /// new one. A delete keeps its record until GC, so it adds nothing. A
110    /// copy-on-write set adds the new version.
111    ///
112    /// The one single-record entry point: it seeds from the committed spans
113    /// and derives the ADR-0439 term itself, so no caller re-spells that
114    /// order — a caller holding a seed (the group admission walk) instead
115    /// passes its own term to [`Graph::estimate_redo_delta_with_constraint_growth`].
116    #[doc(hidden)]
117    pub fn estimate_redo_delta(&self, ops: &[RedoOp]) -> crate::memory::RedoDelta {
118        let growth = self.estimate_constraint_key_entry_growth(ops);
119        self.estimate_redo_delta_with_constraint_growth(ops, growth, self.dense_spans())
120            .0
121    }
122
123    /// [`Graph::estimate_redo_delta`] with the constraint-key entry-growth
124    /// term and the dense-span seed supplied by the caller. The group-commit
125    /// admission loop classifies each slot once and passes the delta its walk
126    /// produced, so the slot's ops are not re-classified here (ADR-0439).
127    /// `spans` is the seed — the walk's advanced dense spans for a group (its
128    /// slots price against what the group already reserved), the committed
129    /// ones for a single-record caller — and the advanced spans come back OUT
130    /// beside the delta, never written through the seed: the caller keeps them
131    /// only for an accepted slot, so a refused estimate leaves no phantom rung
132    /// behind.
133    #[doc(hidden)]
134    pub fn estimate_redo_delta_with_constraint_growth(
135        &self,
136        ops: &[RedoOp],
137        constraint_growth: i64,
138        spans: crate::memory::DenseSpans,
139    ) -> (crate::memory::RedoDelta, crate::memory::DenseSpans) {
140        let before = self.index_charge();
141        let after = self.charge_after_ops(ops);
142        let (
143            crate::memory::RedoDelta {
144                total: mut delta,
145                mut spill,
146            },
147            chain,
148        ) = crate::memory::estimate_redo_delta(
149            &self.interner,
150            ops,
151            |id| self.node(id),
152            |id| self.rel_form(id),
153            |id| self.node_chain_shape(id),
154            |id| self.rel_chain_shape(id),
155            |s| crate::memory::chain_bytes(s, node_version_stride()),
156            |s| crate::memory::chain_bytes(s, rel_version_stride()),
157            spans,
158            &after,
159        );
160        let (adj, adj_spans) = self.estimate_adj_delta(ops, &spans);
161        delta += adj.refusable + adj.spill;
162        spill += adj.spill;
163        delta += self.estimate_intern_delta(ops);
164        // LABS-370 (security follow-up): the count family's entry growth
165        // is committed structure too — an oversized-label write must be
166        // rejected at admission, not after its entries land past the cap
167        // (graph/degree_stats.rs owns the term).
168        delta += self.estimate_stats_entry_growth(ops);
169        // ADR-0439: a constrained write's new entries are committed
170        // structure too — refused at admission, never after they land. The
171        // caller supplies the term: derived by
172        // [`Graph::estimate_constraint_key_entry_growth`] for a single-record
173        // caller,
174        // or the delta the group admission walk already computed.
175        delta += constraint_growth;
176        if before.as_ref() != &after {
177            self.nodes.for_each(|id, vers| {
178                for v in vers.iter() {
179                    let n = v.live.to_node(id, &self.interner);
180                    delta += crate::memory::live_node_account(&n, &after) as i64
181                        - crate::memory::live_node_account(&n, &before) as i64;
182                }
183            });
184        }
185        (
186            crate::memory::RedoDelta {
187                total: delta,
188                spill,
189            },
190            // The one merge of the two advances: the chain spans from the
191            // memory walk, the adjacency and sealed spans from this one — a
192            // seed advanced by every dense-span family the estimate prices,
193            // each walk owning exactly its fields.
194            crate::memory::DenseSpans {
195                node: chain.node,
196                rel: chain.rel,
197                adj_out: adj_spans.adj_out,
198                adj_in: adj_spans.adj_in,
199                sealed_out: adj_spans.sealed_out,
200                sealed_in: adj_spans.sealed_in,
201            },
202        )
203    }
204
205    fn estimate_intern_delta(&self, ops: &[RedoOp]) -> i64 {
206        let mut seen = HashSet::new();
207        let mut extra = 0i64;
208        let mut consider = |s: &str| {
209            if !seen.insert(s.to_string()) {
210                return;
211            }
212            if self.interner.get_id(s).is_none() {
213                extra += crate::memory::interned_string_bytes(s.len()) as i64;
214            }
215        };
216        for op in ops {
217            match op {
218                RedoOp::CreateNode {
219                    labels, properties, ..
220                } => {
221                    for label in labels.iter() {
222                        consider(label);
223                    }
224                    for key in properties.keys() {
225                        consider(key);
226                    }
227                }
228                RedoOp::CreateRel {
229                    rel_type,
230                    properties,
231                    ..
232                } => {
233                    consider(rel_type);
234                    for key in properties.keys() {
235                        consider(key);
236                    }
237                }
238                RedoOp::SetNodeProp { key, .. }
239                | RedoOp::RemoveNodeProp { key, .. }
240                | RedoOp::SetRelProp { key, .. }
241                | RedoOp::RemoveRelProp { key, .. } => consider(key),
242                RedoOp::AddLabels { labels, .. } | RedoOp::RemoveLabels { labels, .. } => {
243                    for label in labels {
244                        consider(label);
245                    }
246                }
247                _ => {}
248            }
249        }
250        extra
251    }
252
253    pub(super) fn index_charge(&self) -> Arc<crate::memory::IndexCharge> {
254        Arc::clone(&self.indexes.charge_cache.lock().unwrap())
255    }
256
257    pub(super) fn refresh_index_charge(&self) {
258        let charge = {
259            let theater = self.theater.lock().unwrap();
260            Arc::new(crate::memory::IndexCharge::from_details(
261                theater.index_details.values(),
262            ))
263        };
264        *self.indexes.charge_cache.lock().unwrap() = charge;
265    }
266
267    fn charge_after_ops(&self, ops: &[RedoOp]) -> crate::memory::IndexCharge {
268        let theater = self.theater.lock().unwrap();
269        let mut details = theater.index_details.clone();
270        drop(theater);
271        crate::redo::project_index_details(&mut details, ops);
272        crate::memory::IndexCharge::from_details(details.values())
273    }
274
275    pub(super) fn charge(&self, delta: i64) {
276        // One policy in three stated cases: nothing to apply (routine —
277        // `charge(0)` is the no-constrained-tuple-moved call), a plain
278        // growth, and a release that is the saturation itself
279        // (`saturating_add_signed` floors at zero and takes the delta's
280        // sign, so no negation that overflows at `i64::MIN`).
281        if delta == 0 {
282            return;
283        }
284        if delta > 0 {
285            self.used_bytes.fetch_add(delta as u64, Ordering::Relaxed);
286            return;
287        }
288        self.used_bytes
289            .try_update(Ordering::Relaxed, Ordering::Relaxed, |u| {
290                Some(u.saturating_add_signed(delta))
291            })
292            .expect("the saturating-add closure never rejects");
293    }
294
295    pub(super) fn charge_node_swap(&self, before: Option<&Node>, after: Option<&Node>) {
296        let charge = self.index_charge();
297        let b = before
298            .map(|n| crate::memory::live_node_account(n, &charge))
299            .unwrap_or(0);
300        let a = after
301            .map(|n| crate::memory::live_node_account(n, &charge))
302            .unwrap_or(0);
303        self.charge(a as i64 - b as i64);
304    }
305
306    pub(super) fn charge_rel_after_edit(
307        &self,
308        id: RelId,
309        before_bytes: u64,
310        before_shape: ChainShape,
311    ) {
312        let after_shape = self.rel_chain_shape(id);
313        let after_bytes = self.visible_rel_account(id);
314        if after_shape != before_shape {
315            let growth =
316                crate::memory::chain_growth(before_shape, after_shape, rel_version_stride());
317            self.charge(after_bytes as i64 + growth);
318        } else {
319            self.charge(after_bytes as i64 - before_bytes as i64);
320        }
321    }
322
323    #[cfg(test)]
324    pub(super) fn node_chain_len(&self, id: NodeId) -> usize {
325        self.nodes.get(&id).map_or(0, |v| v.len())
326    }
327
328    pub(super) fn node_chain_shape(&self, id: NodeId) -> ChainShape {
329        self.nodes
330            .get(&id)
331            .map_or(ChainShape::Absent, |v| v.shape())
332    }
333
334    pub(super) fn rel_chain_shape(&self, id: RelId) -> ChainShape {
335        self.rels.get(&id).map_or(ChainShape::Absent, |v| v.shape())
336    }
337
338    /// Copy-on-write keeps the previous version. An in-place edit replaces it.
339    pub(super) fn charge_node_after_edit(
340        &self,
341        id: NodeId,
342        before: Option<&Node>,
343        before_shape: ChainShape,
344    ) {
345        let after = self.node(id);
346        let after_shape = self.node_chain_shape(id);
347        if after_shape != before_shape {
348            let charge = self.index_charge();
349            let added = after
350                .as_ref()
351                .map(|n| crate::memory::live_node_account(n, &charge))
352                .unwrap_or(0);
353            let growth =
354                crate::memory::chain_growth(before_shape, after_shape, node_version_stride());
355            self.charge(added as i64 + growth);
356        } else {
357            self.charge_node_swap(before, after.as_ref());
358        }
359    }
360}