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::mem::size_of;
7use std::sync::Arc;
8
9use relate_core::{Error, Node, NodeId, RelId};
10
11use super::adjacency::{AdjSide, ChunkHops};
12use super::*;
13use crate::adjacency::{AdjHop, SealedRegion, Supersede, MAX_SPAN_TYPES};
14
15impl Graph {
16    /// Live graph + index logical bytes (ADR-0042, ADR-0202).
17    pub fn used_bytes(&self) -> u64 {
18        self.used_bytes
19            .load(Ordering::Relaxed)
20            .saturating_add(self.interner.bytes())
21    }
22
23    /// Full walk of retained versions, adjacency, and the interner
24    /// (test / `rebuild_indexes` oracle).
25    pub fn accounted_bytes(&self) -> u64 {
26        self.structure_bytes().saturating_add(self.interner.bytes())
27    }
28
29    pub(super) fn structure_bytes(&self) -> u64 {
30        let charge = self.index_charge();
31        let mut n = 0u64;
32        n = n.saturating_add(self.nodes.array_bytes());
33        self.nodes.for_each(|_id, vers| {
34            n = n.saturating_add(crate::memory::chain_bytes(
35                vers.shape(),
36                node_version_stride(),
37            ));
38            for v in vers.iter() {
39                n = n.saturating_add(crate::memory::live_node_account_live(
40                    v.live,
41                    &self.interner,
42                    &charge,
43                ));
44            }
45        });
46        n = n.saturating_add(self.rels.array_bytes());
47        self.rels.for_each(|_id, vers| {
48            n = n.saturating_add(crate::memory::chain_bytes(
49                vers.shape(),
50                rel_version_stride(),
51            ));
52            for v in vers.iter() {
53                n = n.saturating_add(crate::memory::live_rel_account_live(v.live));
54            }
55        });
56        // Each side's slot arrays and retained delta entries, and the sealed
57        // arenas (ADR-0551 / ADR-0599) — the arena bytes, the 12-byte
58        // entries, the tombstones, and the dense span tables that index
59        // them — the term the heap census reads as `slot_bytes`.
60        for side in [self.out_side(), self.in_side()] {
61            n = n.saturating_add(side.delta().array_bytes());
62            side.delta()
63                .for_each(|_id, adj| n = n.saturating_add(adj.floor_bytes()));
64        }
65        n = n.saturating_add(self.sealed_floor());
66        // LABS-351 / LABS-370: the degree histograms and the count
67        // bundle's charged maps are retained structure — the recount
68        // oracle must include them or the incremental entry charges
69        // drift from it (the #398 lesson). Each family's term lives
70        // with the family (graph/degree_stats.rs,
71        // graph/count_state.rs) and composes here, at the oracle's
72        // one site, beside the constraint-key term.
73        n = n.saturating_add(self.degree_stats_structure_bytes());
74        n = n.saturating_add(self.count_state_structure_bytes());
75        // ADR-0439: the committed constraint-key map is retained structure
76        // too; it carries the bytes each entry was charged, so the recount
77        // and the incremental charge cannot drift.
78        n = n.saturating_add(self.constraint_keys_structure_bytes());
79        n
80    }
81
82    pub fn recompute_used(&self) {
83        self.used_bytes
84            .store(self.structure_bytes(), Ordering::Relaxed);
85    }
86
87    /// Live-size delta of `ops`. Nodes are accounted under the charge in
88    /// force after `ops`; when that differs from the current charge (DDL in
89    /// the batch), every retained version — including ones `ops` tombstone —
90    /// is moved from the old charge to the new one. A delete keeps its
91    /// record until GC, so it adds nothing. A copy-on-write set adds the
92    /// new version.
93    pub fn estimate_redo_delta(&self, ops: &[RedoOp]) -> i64 {
94        self.estimate_redo_delta_with_constraint_growth(ops, None)
95            .total
96    }
97
98    /// [`Graph::estimate_redo_delta`] with the constraint-key entry-growth
99    /// term optionally supplied by the caller. The group-commit admission
100    /// loop classifies each slot once and passes the delta its walk produced,
101    /// so the slot's ops are not re-classified here (ADR-0439).
102    #[doc(hidden)]
103    pub fn estimate_redo_delta_with_constraint_growth(
104        &self,
105        ops: &[RedoOp],
106        constraint_growth: Option<i64>,
107    ) -> crate::memory::RedoDelta {
108        let before = self.index_charge();
109        let after = self.charge_after_ops(ops);
110        let crate::memory::RedoDelta {
111            total: mut delta,
112            mut spill,
113        } = crate::memory::estimate_redo_delta(
114            &self.interner,
115            ops,
116            |id| self.node(id),
117            |id| self.rel_form(id),
118            |id| self.node_chain_shape(id),
119            |id| self.rel_chain_shape(id),
120            |s| crate::memory::chain_bytes(s, node_version_stride()),
121            |s| crate::memory::chain_bytes(s, rel_version_stride()),
122            self.nodes.span(),
123            self.rels.span(),
124            &after,
125        );
126        let adj = self.estimate_adj_delta(ops);
127        delta += adj.refusable + adj.spill;
128        spill += adj.spill;
129        delta += self.estimate_intern_delta(ops);
130        // LABS-370 (security follow-up): the count family's entry growth
131        // is committed structure too — an oversized-label write must be
132        // rejected at admission, not after its entries land past the cap
133        // (graph/degree_stats.rs owns the term).
134        delta += self.estimate_stats_entry_growth(ops);
135        // ADR-0439: a constrained write's new entries are committed
136        // structure too — refused at admission, never after they land. The
137        // group path supplies the delta its admission walk already computed.
138        delta += match constraint_growth {
139            Some(growth) => growth,
140            None => self.estimate_constraint_key_entry_growth(ops),
141        };
142        if before.as_ref() != &after {
143            self.nodes.for_each(|id, vers| {
144                for v in vers.iter() {
145                    let n = v.live.to_node(id, &self.interner);
146                    delta += crate::memory::live_node_account(&n, &after) as i64
147                        - crate::memory::live_node_account(&n, &before) as i64;
148                }
149            });
150        }
151        crate::memory::RedoDelta {
152            total: delta,
153            spill,
154        }
155    }
156
157    /// The adjacency share of a batch's live-size delta, split into the
158    /// refusable growth — a create's hop and slot growth (dense span or the
159    /// side-map entry a wide id takes, as the store's own estimator charges
160    /// it), plus a founding delete's dense side-table span — and the spill
161    /// the checkpoint fold reclaims: a delete's region, chunk, and tombstone
162    /// terms, and the side-map entry a founding delete at a wide id takes
163    /// (ADR-0529).
164    pub(super) fn estimate_adj_delta(&self, ops: &[RedoOp]) -> AdjDelta {
165        let mut out = SideAdmission::new(self.out_side());
166        let mut inn = SideAdmission::new(self.in_side());
167        let mut fresh_ids = FreshIds::new();
168        let mut delta = AdjDelta::default();
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: PendingTombstones = HashMap::new();
178        let mut pending_in: PendingTombstones = 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                    delta.refusable += out.create(*start, type_id) + inn.create(*end, type_id);
191                }
192                RedoOp::DeleteRel { id } => {
193                    let Some((start, end, type_id)) = created
194                        .get(id)
195                        .copied()
196                        // The store's rels answer through the one live-identity
197                        // spelling (a dead version's delete tombstones nothing,
198                        // as in the apply path).
199                        .or_else(|| self.rel_live_identity(*id))
200                    else {
201                        continue;
202                    };
203                    for (pending, node) in [(&mut pending_out, start), (&mut pending_in, end)] {
204                        pending
205                            .entry(node)
206                            .or_default()
207                            .entry(type_id)
208                            .or_default()
209                            .insert(*id);
210                    }
211                }
212                _ => {}
213            }
214        }
215        // Each delete records one tombstone per endpoint that does not hold
216        // one yet (ADR-0551); the region, chunk, and tombstone terms are
217        // reclaimed at the checkpoint fold, so they are spill and never
218        // refuse a batch (ADR-0529: a delete at the cap commits). The
219        // founding side-table slot is the exception — the dense span only
220        // grows (ADR-0086) — so it stays refusable.
221        delta + self.estimate_delete_spill(&pending_out, &pending_in, Supersede::Deleted)
222    }
223
224    /// The adjacency tier's structural limits (ADR-0599), the ones its
225    /// field widths state: a node holds at most [`MAX_SPAN_TYPES`] distinct
226    /// rel types in one direction (the span length's `u16`), and one
227    /// direction's arena at most `u32::MAX` stream bytes (the entry
228    /// offset's `u32`). Enforced here, at admission, before the redo is
229    /// logged — the tier's own mutation paths are infallible by design, so
230    /// the wall they must never hit is refused upstream. A delete never
231    /// breaches either: it founds a sealed entry only for a type the node
232    /// already holds, and its tombstone terms reclaim at the fold.
233    ///
234    /// `earlier` are the ops of slots this group commit already accepted:
235    /// the type wall is per group, not per slot — two slots that each add
236    /// types under the bound must be refused when their combined types
237    /// cross it, so this slot's creates are counted on top of the group's.
238    /// Each earlier slot passed the same walk at its own admission, so the
239    /// combined walk never fails on the earlier batches alone.
240    pub fn enforce_adjacency_limits(&self, ops: &[RedoOp], earlier: &[&[RedoOp]]) -> Result<()> {
241        let mut fresh_ids = FreshIds::new();
242        let mut out = TypeWall::new(self.out_side());
243        let mut inn = TypeWall::new(self.in_side());
244        // A second accumulator beside `SideAdmission`, stated: the byte
245        // estimate is per slot and only runs under a configured size limit,
246        // while the wall is per group and unconditional — the two walks
247        // cannot share a gate.
248        let mut growth = 0u64;
249        for batch in earlier.iter().copied().chain(std::iter::once(ops)) {
250            for op in batch {
251                if let RedoOp::CreateRel {
252                    start,
253                    end,
254                    rel_type,
255                    ..
256                } = op
257                {
258                    let type_id = fresh_ids.resolve(self, rel_type);
259                    out.record(*start, type_id)?;
260                    inn.record(*end, type_id)?;
261                    // One stored hop per endpoint reaches an arena at the
262                    // fold. A delete adds none: its tombstones live in the
263                    // entry column, never in the arena's byte buffer, so a
264                    // delete is never refused for a bound it shrinks toward
265                    // (ADR-0529's rule for the byte cap, on the field bound).
266                    growth = growth.saturating_add(2 * size_of::<AdjHop>() as u64);
267                }
268            }
269        }
270        // The arena wall, per direction — each arena's own streams plus this
271        // batch's sealed-tier growth against its own offset field. The
272        // store's whole live charge is deliberately not compared: it prices
273        // structures no arena holds, and refusing on it would freeze a store
274        // whose live bytes sit above the bound — deletes included. A fold
275        // the arena itself refuses degrades instead (see `put_chunk`), so
276        // this wall is the early, loud spelling of the same bound.
277        for arena_bytes in self
278            .sides(relate_ir::Direction::Both)
279            .map(|(side, _)| side.sealed().arena_bytes())
280        {
281            if sealed_arena_breaches(arena_bytes, growth) {
282                return Err(Error::capacity_sealed_arena(
283                    arena_bytes.saturating_add(growth),
284                    u32::MAX as u64,
285                ));
286            }
287        }
288        Ok(())
289    }
290
291    /// The batch's delete terms: every delete
292    /// records one tombstone per endpoint that does not hold one yet
293    /// (ADR-0551) — a sealed chunk grows its tombstone vec, a never-sealed
294    /// type adds its on-demand chunk to the endpoint's region, all reclaimed
295    /// at the next checkpoint fold and so spill that never refuses a batch
296    /// (ADR-0529) — while a founding delete's dense side-table span is
297    /// permanent (ADR-0086) and stays refusable; its side-map entry,
298    /// reclaimed with the region, is spill like the rest.
299    fn estimate_delete_spill(
300        &self,
301        pending_out: &PendingTombstones,
302        pending_in: &PendingTombstones,
303        supersede: Supersede,
304    ) -> AdjDelta {
305        let sealed_slot = sealed_slot();
306        let sealed_overflow = crate::memory::overflow_entry_bytes(sealed_slot);
307        price_side(
308            self.out_side().sealed(),
309            pending_out,
310            sealed_slot,
311            sealed_overflow,
312            supersede,
313        ) + price_side(
314            self.in_side().sealed(),
315            pending_in,
316            sealed_slot,
317            sealed_overflow,
318            supersede,
319        )
320    }
321
322    /// One write event's sealed-tier price on both endpoints' sides — the
323    /// per-event spelling of [`price_side`], the one formula the admission
324    /// estimate prices whole batches with. A delete records its tombstone on
325    /// demand, founding the entry when the region holds none (ADR-0551); a
326    /// reposition supersedes only a position a sealed chunk holds, so its
327    /// missing-chunk arm prices nothing. Priced before the event lands, so
328    /// the counts the terms read are the pre-mutation ones.
329    pub(super) fn price_sealed_event(
330        &self,
331        start: NodeId,
332        end: NodeId,
333        type_id: u32,
334        id: RelId,
335        supersede: Supersede,
336    ) -> (i64, i64) {
337        // The one-event spelling of [`price_side`]: the per-key and per-node
338        // bodies called once per endpoint, no nested batch maps.
339        let ids = HashSet::from([id]);
340        let sealed_slot = sealed_slot();
341        let sealed_overflow = crate::memory::overflow_entry_bytes(sealed_slot);
342        let mut refusable = 0i64;
343        let mut spill = 0i64;
344        for (sealed, node) in [
345            (self.out_side().sealed(), start),
346            (self.in_side().sealed(), end),
347        ] {
348            let region = sealed.region(node);
349            let (mut entries, mut tombstones) = sealed.entry_counts();
350            spill += price_sealed_key(
351                region,
352                type_id,
353                &ids,
354                &mut entries,
355                &mut tombstones,
356                supersede,
357            );
358            let mut span = sealed.span();
359            let (node_refusable, node_spill) = price_sealed_node(
360                &mut span,
361                region,
362                node,
363                sealed_slot,
364                sealed_overflow,
365                supersede,
366            );
367            refusable += node_refusable;
368            spill += node_spill;
369        }
370        (refusable, spill)
371    }
372
373    fn estimate_intern_delta(&self, ops: &[RedoOp]) -> i64 {
374        let mut seen = HashSet::new();
375        let mut extra = 0i64;
376        let mut consider = |s: &str| {
377            if !seen.insert(s.to_string()) {
378                return;
379            }
380            if self.interner.get_id(s).is_none() {
381                extra += crate::memory::interned_string_bytes(s.len()) as i64;
382            }
383        };
384        for op in ops {
385            match op {
386                RedoOp::CreateNode {
387                    labels, properties, ..
388                } => {
389                    for label in labels.iter() {
390                        consider(label);
391                    }
392                    for key in properties.keys() {
393                        consider(key);
394                    }
395                }
396                RedoOp::CreateRel {
397                    rel_type,
398                    properties,
399                    ..
400                } => {
401                    consider(rel_type);
402                    for key in properties.keys() {
403                        consider(key);
404                    }
405                }
406                RedoOp::SetNodeProp { key, .. }
407                | RedoOp::RemoveNodeProp { key, .. }
408                | RedoOp::SetRelProp { key, .. }
409                | RedoOp::RemoveRelProp { key, .. } => consider(key),
410                RedoOp::AddLabels { labels, .. } | RedoOp::RemoveLabels { labels, .. } => {
411                    for label in labels {
412                        consider(label);
413                    }
414                }
415                _ => {}
416            }
417        }
418        extra
419    }
420
421    pub(super) fn index_charge(&self) -> Arc<crate::memory::IndexCharge> {
422        Arc::clone(&self.indexes.charge_cache.lock().unwrap())
423    }
424
425    pub(super) fn refresh_index_charge(&self) {
426        let charge = {
427            let theater = self.theater.lock().unwrap();
428            Arc::new(crate::memory::IndexCharge::from_details(
429                theater.index_details.values(),
430            ))
431        };
432        *self.indexes.charge_cache.lock().unwrap() = charge;
433    }
434
435    fn charge_after_ops(&self, ops: &[RedoOp]) -> crate::memory::IndexCharge {
436        let theater = self.theater.lock().unwrap();
437        let mut details = theater.index_details.clone();
438        drop(theater);
439        crate::redo::project_index_details(&mut details, ops);
440        crate::memory::IndexCharge::from_details(details.values())
441    }
442
443    pub(super) fn charge(&self, delta: i64) {
444        if delta > 0 {
445            self.used_bytes.fetch_add(delta as u64, Ordering::Relaxed);
446        } else if delta < 0 {
447            let sub = (-delta) as u64;
448            atomic_fetch_update!(self.used_bytes, Ordering::Relaxed, Ordering::Relaxed, |u| {
449                Some(u.saturating_sub(sub))
450            })
451            .expect("the saturating-sub closure never rejects");
452        }
453    }
454
455    pub(super) fn charge_node_swap(&self, before: Option<&Node>, after: Option<&Node>) {
456        let charge = self.index_charge();
457        let b = before
458            .map(|n| crate::memory::live_node_account(n, &charge))
459            .unwrap_or(0);
460        let a = after
461            .map(|n| crate::memory::live_node_account(n, &charge))
462            .unwrap_or(0);
463        self.charge(a as i64 - b as i64);
464    }
465
466    pub(super) fn charge_rel_after_edit(
467        &self,
468        id: RelId,
469        before_bytes: u64,
470        before_shape: ChainShape,
471    ) {
472        let after_shape = self.rel_chain_shape(id);
473        let after_bytes = self.visible_rel_account(id);
474        if after_shape != before_shape {
475            let growth = crate::memory::chain_bytes(after_shape, rel_version_stride()) as i64
476                - crate::memory::chain_bytes(before_shape, rel_version_stride()) as i64;
477            self.charge(after_bytes as i64 + growth);
478        } else {
479            self.charge(after_bytes as i64 - before_bytes as i64);
480        }
481    }
482
483    #[cfg(test)]
484    pub(super) fn node_chain_len(&self, id: NodeId) -> usize {
485        self.nodes.get(&id).map_or(0, |v| v.len())
486    }
487
488    pub(super) fn node_chain_shape(&self, id: NodeId) -> ChainShape {
489        self.nodes
490            .get(&id)
491            .map_or(ChainShape::Absent, |v| v.shape())
492    }
493
494    pub(super) fn rel_chain_shape(&self, id: RelId) -> ChainShape {
495        self.rels.get(&id).map_or(ChainShape::Absent, |v| v.shape())
496    }
497
498    /// Copy-on-write keeps the previous version. An in-place edit replaces it.
499    pub(super) fn charge_node_after_edit(
500        &self,
501        id: NodeId,
502        before: Option<&Node>,
503        before_shape: ChainShape,
504    ) {
505        let after = self.node(id);
506        let after_shape = self.node_chain_shape(id);
507        if after_shape != before_shape {
508            let charge = self.index_charge();
509            let added = after
510                .as_ref()
511                .map(|n| crate::memory::live_node_account(n, &charge))
512                .unwrap_or(0);
513            let growth = crate::memory::chain_bytes(after_shape, node_version_stride()) as i64
514                - crate::memory::chain_bytes(before_shape, node_version_stride()) as i64;
515            self.charge(added as i64 + growth);
516        } else {
517            self.charge_node_swap(before, after.as_ref());
518        }
519    }
520}
521
522/// The admission estimates' fresh-name resolver (LABS-425, stellar round
523/// 1): a name the interner does not know — a label or rel type the
524/// not-yet-applied batch mints — resolves to a descending id below the
525/// committed range, one id per distinct name. Both estimate terms
526/// ([`Graph::estimate_adj_delta`] here,
527/// [`Graph::estimate_stats_entry_growth`] in
528/// graph/degree_stats_estimate.rs) resolved this ladder by hand before;
529/// the descending-id collision invariant (fresh ids never collide with
530/// committed ids or each other) now lives in exactly one place.
531#[derive(Clone, Debug, PartialEq)]
532pub(super) struct FreshIds {
533    fresh: HashMap<String, u32>,
534    next: u32,
535}
536
537impl FreshIds {
538    pub(super) fn new() -> Self {
539        Self {
540            fresh: HashMap::new(),
541            next: u32::MAX,
542        }
543    }
544
545    /// The interned id, else this batch's earlier mint, else a new
546    /// descending id minted and memoized.
547    pub(super) fn resolve(&mut self, g: &Graph, name: &str) -> u32 {
548        g.interner
549            .get_id(name)
550            .or_else(|| self.fresh.get(name).copied())
551            .unwrap_or_else(|| {
552                let id = self.next;
553                self.next = self.next.saturating_sub(1);
554                self.fresh.insert(name.to_string(), id);
555                id
556            })
557    }
558}
559
560/// A batch's pending delete tombstones on one side: per node, per rel
561/// type, the rel ids that will record one.
562type PendingTombstones = HashMap<NodeId, HashMap<u32, HashSet<RelId>>>;
563
564/// An adjacency estimate's two shares (ADR-0529): `refusable` growth is
565/// committed structure an over-cap batch is refused for; `spill` is what the
566/// checkpoint fold reclaims, so it never refuses a batch.
567#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
568pub(super) struct AdjDelta {
569    pub(super) refusable: i64,
570    pub(super) spill: i64,
571}
572
573impl std::ops::Add for AdjDelta {
574    type Output = Self;
575
576    fn add(self, other: Self) -> Self {
577        Self {
578            refusable: self.refusable + other.refusable,
579            spill: self.spill + other.spill,
580        }
581    }
582}
583
584/// What one [`place_in_span`](crate::memory::place_in_span) answer charges
585/// — the one mapping from the placement policy's result to bytes, shared by
586/// the create loop and the delete phase: `dense` growth is permanent
587/// structure, `side_entry` the reclaimable entry a wide id takes. An id the
588/// array cannot index is refused by the commit's own validation before
589/// anything applies, so it prices nothing.
590struct PlacementCharge {
591    dense: i64,
592    side_entry: bool,
593}
594
595fn place(span: &mut usize, node: NodeId, slot: u64) -> PlacementCharge {
596    match crate::memory::place_in_span(span, node, slot) {
597        None | Some(crate::memory::SpanPlacement::Inside) => PlacementCharge {
598            dense: 0,
599            side_entry: false,
600        },
601        Some(crate::memory::SpanPlacement::Grew { bytes, .. }) => PlacementCharge {
602            dense: bytes as i64,
603            side_entry: false,
604        },
605        Some(crate::memory::SpanPlacement::SideEntry) => PlacementCharge {
606            dense: 0,
607            side_entry: true,
608        },
609    }
610}
611
612/// One side's create-admission state: the committed pair, the dense span the
613/// batch has grown so far, the wide ids already priced, and the simulated
614/// chunk lists the batch's creates have built. One op touches both sides by
615/// the same rule, so the loop calls [`SideAdmission::create`] once per
616/// endpoint.
617struct SideAdmission<'a> {
618    side: AdjSide<'a>,
619    span: usize,
620    wide: HashSet<NodeId>,
621    pending: HashMap<NodeId, Vec<ChunkHops>>,
622    slot: u64,
623    overflow: u64,
624}
625
626impl<'a> SideAdmission<'a> {
627    fn new(side: AdjSide<'a>) -> Self {
628        Self {
629            span: side.delta().span(),
630            side,
631            wide: HashSet::new(),
632            pending: HashMap::new(),
633            slot: adj_slot(),
634            overflow: crate::memory::overflow_entry_bytes(adj_value()),
635        }
636    }
637
638    /// The refusable bytes one created rel adds at `node` on this side: the
639    /// node's slot when it has no adjacency entry yet, and the hop growth.
640    fn create(&mut self, node: NodeId, type_id: u32) -> i64 {
641        let mut bytes = 0;
642        if !self.side.delta().contains_key(&node) {
643            // A dense growth is committed structure (refusable); a
644            // side-map entry is priced once per node per batch — the loop
645            // can revisit a node across its ops, so the dedupe is here.
646            let placed = place(&mut self.span, node, self.slot);
647            bytes += placed.dense;
648            if placed.side_entry && self.wide.insert(node) {
649                bytes += self.overflow as i64;
650            }
651        }
652        bytes
653            + bump_adj(&mut self.pending, node, type_id, || {
654                self.side.hop_counts(node)
655            })
656    }
657}
658
659/// One direction's share of the span-length limit
660/// ([`Graph::enforce_adjacency_limits`]): per touched node, the distinct
661/// types it already holds and the new types this batch would add. Held is
662/// the sealed span's own entries unioned with the delta chunks — the same
663/// vocabulary the span length counts, never the hop-bearing chunk list
664/// alone (a type whose delta chunk a fold's fully-reclaimed arm removed
665/// keeps its sealed entry, so `hop_counts` would undercount it). A type
666/// the node holds is free; a fresh one counts against
667/// [`MAX_SPAN_TYPES`].
668struct TypeWall<'a> {
669    side: AdjSide<'a>,
670    nodes: HashMap<NodeId, (HashSet<u32>, HashSet<u32>)>,
671}
672
673impl<'a> TypeWall<'a> {
674    fn new(side: AdjSide<'a>) -> Self {
675        Self {
676            side,
677            nodes: HashMap::new(),
678        }
679    }
680
681    /// One created rel's `(node, type)` pair. The held set is read once
682    /// per touched node; the fresh set dedupes a batch that repeats a new
683    /// type on the same node.
684    fn record(&mut self, node: NodeId, type_id: u32) -> Result<()> {
685        let (held, fresh) = self.nodes.entry(node).or_insert_with(|| {
686            let mut held: HashSet<u32> = self
687                .side
688                .sealed()
689                .region(node)
690                .map(|r| r.type_ids().into_iter().collect())
691                .unwrap_or_default();
692            if let Some(adj) = self.side.delta().get(&node) {
693                held.extend(adj.chunks.iter().map(|c| c.type_id));
694            }
695            (held, HashSet::new())
696        });
697        if !held.contains(&type_id) && fresh.insert(type_id) {
698            let count = held.len() + fresh.len();
699            if count > MAX_SPAN_TYPES {
700                return Err(Error::capacity_adjacency_types(
701                    count as u64,
702                    MAX_SPAN_TYPES as u64,
703                ));
704            }
705        }
706        Ok(())
707    }
708}
709
710/// The entry-offset bound ([`Graph::enforce_adjacency_limits`]): one
711/// arena's own stream bytes plus the batch's growth stay under the `u32`
712/// the entry offsets address. Saturating so an over-bound store refuses,
713/// never wraps.
714pub(super) fn sealed_arena_breaches(arena_bytes: u64, growth: u64) -> bool {
715    !crate::adjacency::arena_admits(arena_bytes, growth)
716}
717
718impl Graph {
719    /// The sealed tier's whole reserved heap, both directions — the recount
720    /// oracle's term ([`Graph::structure_bytes`]); the write path charges
721    /// its events per region through [`Graph::price_sealed_event`] instead
722    /// (ADR-0599).
723    pub(super) fn sealed_floor(&self) -> u64 {
724        let mut n = 0u64;
725        for sealed in self
726            .sides(relate_ir::Direction::Both)
727            .map(|(side, _)| side.sealed())
728        {
729            let tier = sealed.tier_bytes();
730            n = n.saturating_add(tier.arena);
731            n = n.saturating_add(tier.index);
732        }
733        n
734    }
735}
736
737/// One side's share of the sealed-tier terms
738/// ([`Graph::estimate_delete_spill`](Graph::estimate_delete_spill)'s phase
739/// 2, and the write path's per-event spelling
740/// [`Graph::price_sealed_event`]): per
741/// node, the dense span-table growth (permanent, refusable), the entry-array
742/// growth across every joining type — one before-and-after term per region,
743/// never one per type, or the reserved model's pow2 steps misprice a batch
744/// that joins several — then each key's own terms (all fold-reclaimed,
745/// spill): a sealed chunk's tombstone-vec growth, or a joining chunk's
746/// tombstones. `supersede` selects the missing-chunk arm: a delete records
747/// its tombstone on demand and so founds the entry (ADR-0551); a
748/// reposition only supersedes a position a sealed chunk holds
749/// ([`AdjSide::reposition`]'s delta-only arm writes no tombstone), so a
750/// missing chunk prices nothing.
751fn price_side(
752    sealed: &SealedArena,
753    pending: &PendingTombstones,
754    sealed_slot: u64,
755    sealed_overflow: u64,
756    supersede: Supersede,
757) -> AdjDelta {
758    let mut span = sealed.span();
759    let (mut entries, mut tombstones) = sealed.entry_counts();
760    let mut priced = AdjDelta::default();
761    for (node, keys) in pending {
762        // One key loop prices every key's own term: a chunk the region
763        // already holds grows its tombstone vec (a delete after a
764        // reposition updates the existing slot in place), a type the
765        // region does not hold joins it, inserting its zero-hop entry and
766        // bringing its tombstones — priced once, here, never again in a
767        // region-level arm.
768        let region = sealed.region(*node);
769        for (type_id, ids) in keys {
770            priced.spill += price_sealed_key(
771                region,
772                *type_id,
773                ids,
774                &mut entries,
775                &mut tombstones,
776                supersede,
777            );
778        }
779        // The region-level term, once per node: a founding delete grows the
780        // node's dense span permanently (refusable). Each node reaches this
781        // arm once (`pending` is keyed by node), so the entry prices
782        // unconditionally — the per-batch dedupe is the create loop's, where
783        // a node can recur.
784        let (node_refusable, node_spill) = price_sealed_node(
785            &mut span,
786            region,
787            *node,
788            sealed_slot,
789            sealed_overflow,
790            supersede,
791        );
792        priced.refusable += node_refusable;
793        priced.spill += node_spill;
794    }
795    priced
796}
797
798/// One `(node, key)` entry's sealed-tier spill terms — the per-key body
799/// [`price_side`] loops and [`Graph::price_sealed_event`] calls once per
800/// endpoint. `entries`/`tombstones` are the running entry-column counts a
801/// joining chunk grows.
802fn price_sealed_key(
803    region: Option<SealedRegion<'_>>,
804    type_id: u32,
805    ids: &HashSet<RelId>,
806    entries: &mut usize,
807    tombstones: &mut usize,
808    supersede: Supersede,
809) -> i64 {
810    match region.filter(|r| r.has_chunk(type_id)) {
811        Some(region) => {
812            let fresh = region.fresh_tombstone_count(type_id, ids);
813            region.tombstone_growth_bytes(type_id, fresh) as i64
814        }
815        None if supersede == Supersede::Deleted => {
816            let mut spill = crate::adjacency::fresh_sealed_chunk_floor_bytes(ids.len()) as i64;
817            spill += crate::adjacency::entry_column_growth(*entries, *tombstones, 1) as i64;
818            *entries += 1;
819            *tombstones += 1;
820            spill
821        }
822        None => 0,
823    }
824}
825
826/// One node's founding-delete span term — the per-node body [`price_side`]
827/// and [`Graph::price_sealed_event`] share: the dense span a founding delete
828/// grows (refusable) or the side-map entry it takes (spill, reclaimed with
829/// the region it founds).
830fn price_sealed_node(
831    span: &mut usize,
832    region: Option<SealedRegion<'_>>,
833    node: NodeId,
834    sealed_slot: u64,
835    sealed_overflow: u64,
836    supersede: Supersede,
837) -> (i64, i64) {
838    if region.is_none() && supersede == Supersede::Deleted {
839        // The one placement mapping, shared with the create loop: dense
840        // growth is permanent structure, the side entry reclaimable.
841        let charge = place(span, node, sealed_slot);
842        return (
843            charge.dense,
844            i64::from(charge.side_entry) * sealed_overflow as i64,
845        );
846    }
847    (0, 0)
848}
849
850fn bump_adj(
851    sim: &mut HashMap<NodeId, Vec<ChunkHops>>,
852    node: NodeId,
853    type_id: u32,
854    init: impl FnOnce() -> Vec<ChunkHops>,
855) -> i64 {
856    let chunks = sim.entry(node).or_insert_with(init);
857    let before = crate::adjacency::adjacency_bytes(chunks.iter().map(|c| c.hops));
858    if let Some(slot) = chunks.iter_mut().find(|c| c.type_id == type_id) {
859        slot.hops += 1;
860    } else {
861        chunks.push(ChunkHops { type_id, hops: 1 });
862    }
863    crate::adjacency::adjacency_bytes(chunks.iter().map(|c| c.hops)) as i64 - before as i64
864}