Skip to main content

relate_executor/graph/
mod.rs

1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
3use std::sync::{Arc, Mutex};
4
5use relate_catalog::{Catalog, ConstraintDef, IndexDef};
6use relate_core::{Namespace, Node, NodeId, RelId, Relationship, Result, Value};
7
8use crate::adjacency::{SealedAdj, TypedAdj};
9use crate::group_key::GroupKey;
10use crate::memory::ChainShape;
11use crate::pull_identity::PullIdentityIndex;
12use crate::redo::{self, PullKind, RedoOp};
13use crate::store::{Interner, LiveNode, LiveRel, RelTypes};
14
15use adjacency::{adj_insert, adj_reposition};
16use constraint_keys::ConstraintKeyIndex;
17use count_state::{CountDelta, CountStats};
18
19// The count-only reader's probe shape (LABS-370 round 3, F-1-5): re-exported
20// for the recognizer in `exec` — the window itself lives on `Graph`.
21pub(crate) use count_state::CountProbe;
22
23mod engine_api;
24
25mod adjacency;
26mod apply_redo;
27// The research-only heap-census harness (ADR-0476 quarantine shape): the
28// testing example of the same name reads it through the research feature.
29// Private module with root re-exports only (one public path per item).
30#[cfg(feature = "research")]
31pub(crate) mod census;
32mod chain;
33mod conflict;
34pub(crate) mod constraint_keys;
35mod count_state;
36mod declared;
37mod degree_stats;
38mod degree_stats_estimate;
39mod degree_stats_incident;
40mod derived_migration;
41mod entity_mutation;
42mod id_vec;
43mod index;
44mod index_lookup;
45mod index_postings;
46mod label_mutation;
47mod label_probe;
48mod prop_read;
49mod query_stats;
50mod redo_preflight;
51mod rel_postings;
52mod restore;
53mod services;
54// Research-only (speed-of-light kernels), quarantined behind the
55// non-default `research` cargo feature (ADR-0476): absent from every
56// default build and every bundle.
57#[cfg(feature = "research")]
58pub mod sol;
59// Research-only: the live-read family the sol kernel reads (the
60// helpers this quarantine used to inline in the module root; the
61// qpp half retired with its prototype, ADR-0478).
62#[cfg(feature = "research")]
63mod research;
64#[cfg(test)]
65pub(crate) mod test_support;
66mod theater;
67
68pub(crate) use declared::{spatial_holds, trigram_count, RangeSeek, SpatialSeek};
69use declared::{GramIndex, PointIndex, RangeIndex};
70#[cfg(test)]
71pub(crate) use index::CONTAINS_SAMPLE_BOUND;
72use index::{ContainsMemo, Indexes};
73// One canonical provenance type (LABS-643): defined beside the planner's
74// `PatternStats` contract that consumes it, re-exported so the executor's
75// construction sites and tests keep the one path.
76#[cfg(test)]
77pub(crate) use label_probe::take_label_probe_checks;
78pub(crate) use label_probe::LabelProbe;
79pub use query_stats::QueryStats;
80// One public path (index stays private): the whole-graph index-rebuild
81// count the facade's reopen tests read (LABS-1112's empty-replay skip).
82#[cfg(feature = "test-hooks")]
83#[doc(hidden)]
84pub use index::take_index_rebuilds;
85pub use relate_planner::ContainsCount;
86pub(crate) use services::StoreServices;
87
88use theater::TheaterData;
89
90/// The core-store map: integer keys, FxHash — SipHash + the default
91/// hasher on dense engine-generated ids was profiled as a top-2 cost
92/// (LABS-337/LABS-358); ADR-0355's rule: a key that is attacker-writable
93/// must not use it.
94pub(crate) type CoreMap<K, V> = dashmap::DashMap<K, V, crate::hash_seed::FxBuildHasher>;
95
96/// The visible version at `ts` — the one walk every `*_at` read takes
97/// over a version chain (LABS-337's extraction of the previously
98/// five-times-spelled rev-find).
99fn visible_version<Live>(vers: &Chain<Live>, ts: u64) -> Option<VerRef<'_, Live>> {
100    vers.visible_at(ts)
101}
102
103/// The LIVE version — the last `xmax == 0` one, not a ts-probe: the
104/// maintained-statistics paths run inside the write window, where a rel
105/// created earlier in the same batch is invisible at `commit_ts` and one
106/// deleted in the batch keeps a live-looking pre-delete version. The
107/// `xmax == 0` convention is the one every live-version reader in the graph
108/// module uses (`live_label_ids`, the rebuild's live-rel scan, and the
109/// constraint_keys family's snapshots and backfills).
110fn live_version<Live>(vers: &Chain<Live>) -> Option<VerRef<'_, Live>> {
111    vers.live()
112}
113
114/// One live rel row of a wholesale adjacency build — the seam
115/// `rebuild_adj` materializes once and hands to `adjacency::adj_build`
116/// and both rebuild folds (`rebuild_degree_stats`,
117/// `rebuild_count_stats`) consume. It lives here beside [`LabelCache`],
118/// not in the adjacency-accessor sibling: the folds read it without
119/// touching adjacency. Named fields rather than a positional tuple:
120/// `start` and `end` share a type, so a swapped pair would compile and
121/// only the adjacency tests would catch it.
122pub(in crate::graph) struct RelRow {
123    pub(in crate::graph) id: RelId,
124    pub(in crate::graph) start: NodeId,
125    pub(in crate::graph) type_id: u32,
126    pub(in crate::graph) end: NodeId,
127    pub(in crate::graph) ts: Option<i64>,
128}
129
130/// The wholesale rebuild folds' shared label cache: one live-label
131/// read per distinct endpoint node ([`Graph::live_label_ids`]), the
132/// same seam [`Graph::rebuild_count_stats`] and
133/// [`Graph::rebuild_degree_stats`] both fold over — one spelling of
134/// the ensure-then-expect read, never a hand-rolled map per file.
135#[derive(Default)]
136pub(in crate::graph) struct LabelCache(HashMap<NodeId, Vec<u32>>);
137
138impl LabelCache {
139    /// Read `node`'s live labels into the cache exactly once.
140    pub(in crate::graph) fn ensure(&mut self, graph: &Graph, node: NodeId) {
141        self.0
142            .entry(node)
143            .or_insert_with(|| graph.live_label_ids(node));
144    }
145
146    /// The cached labels — the fold ensured the node's entry first, so
147    /// a miss is the fold's own invariant broken, loudly.
148    pub(in crate::graph) fn get(&self, node: NodeId) -> &[u32] {
149        self.0
150            .get(&node)
151            .expect("the fold cached every endpoint's labels")
152            .as_slice()
153    }
154}
155
156/// The store's token resolver (ADR-0541): the facade hands the graph to the
157/// planner beside its statistics, so plan-time resolution reads the same
158/// interner execution does.
159impl relate_names::TokenResolver for Graph {
160    fn resolve(&self, name: &str) -> relate_names::Token {
161        self.interner.resolve(name)
162    }
163}
164
165impl Graph {
166    /// A node's current live labels in the interned domain (u32 ids) —
167    /// the histogram's key domain, read through [`live_version`] rather than
168    /// a snapshot-visible one: the histogram is maintained at create time,
169    /// inside the writing transaction, where the just-created node is not yet
170    /// visible at `commit_ts` (the bug the first version of this read had —
171    /// every bump looped over zero labels). The `xmax == 0` convention
172    /// matches the rebuild's live-rel scan.
173    pub(in crate::graph) fn live_label_ids(&self, node: NodeId) -> Vec<u32> {
174        self.nodes
175            .get(&node)
176            .and_then(|vers| vers.live().map(|v| v.live.labels.clone()))
177            .unwrap_or_default()
178    }
179}
180
181pub(crate) use theater::{apply_show_overlay, DatabasesCatalog, ShowSchema};
182pub use theater::{CheckpointTheater, DatabaseEntry, SchemaSnapshot};
183
184/// `Atomic*::fetch_update` was renamed to `try_update` in Rust 1.95 and
185/// deprecated in 1.99. MSRV is 1.88, where `try_update` does not exist, so
186/// the call keeps the old name. `#[expect(deprecated)]` is wrong here: on
187/// 1.88 the lint does not fire and the build would fail.
188macro_rules! atomic_fetch_update {
189    ($atom:expr, $set:expr, $fetch:expr, $f:expr) => {{
190        #[allow(
191            deprecated,
192            reason = "fetch_update renamed to try_update in 1.99; try_update needs 1.95, MSRV is 1.88"
193        )]
194        {
195            $atom.fetch_update($set, $fetch, $f)
196        }
197    }};
198}
199
200/// An exhaustible `i64` id counter shared by the committed graph counters and
201/// the overlay scratch counters. Both allocate the current value and advance;
202/// both must fail rather than wrap once `i64::MAX` is reached. The two atomic
203/// widths exist because the overlay seeds its counters from the graph's.
204pub(crate) trait ExhaustibleIdCounter {
205    fn try_alloc_id(&self) -> std::result::Result<i64, i64>;
206}
207
208impl ExhaustibleIdCounter for AtomicI64 {
209    fn try_alloc_id(&self) -> std::result::Result<i64, i64> {
210        atomic_fetch_update!(self, Ordering::Relaxed, Ordering::Relaxed, |id| {
211            if (0..i64::MAX).contains(&id) {
212                Some(id + 1)
213            } else {
214                None
215            }
216        })
217    }
218}
219
220impl ExhaustibleIdCounter for AtomicU64 {
221    fn try_alloc_id(&self) -> std::result::Result<i64, i64> {
222        atomic_fetch_update!(self, Ordering::Relaxed, Ordering::Relaxed, |id| {
223            (id < i64::MAX as u64).then_some(id + 1)
224        })
225        .map(|id| id as i64)
226        .map_err(|id| id as i64)
227    }
228}
229
230/// The `DeleteConnectedNode` execution error, shared by every node-delete
231/// path so the message never drifts between them. The class token leads the
232/// payload: live Neo4j 2026.10.1 reports the
233/// `ConstraintVerificationFailed` class (G1001), and the bindings recover
234/// it through the one nested-class scan of still-stringly payloads. The
235/// token composes from the typed class vocabulary, so its spelling cannot
236/// drift from the scan's.
237pub(crate) fn delete_connected_node_error() -> relate_core::Error {
238    relate_core::Error::execution(format!(
239        "{}: DeleteConnectedNode: Cannot delete node with relationships unless DETACH",
240        relate_error::NestedErrorClass::ConstraintVerificationFailed.as_str(),
241    ))
242}
243
244/// The one typed reply for a relationship whose endpoint is not a live node:
245/// the create path's semantic error, shared by the overlay's create, the
246/// primitive's endpoint validation, and the redo preflight.
247pub(crate) fn missing_rel_endpoint_error() -> relate_core::Error {
248    relate_core::Error::semantic("cannot create relationship on missing node")
249}
250
251/// Allocate the next exhaustible id from `counter`, mapping exhaustion to the
252/// caller's `<what> ID exhausted` error.
253pub(crate) fn alloc_exhaustible_id(counter: &impl ExhaustibleIdCounter, what: &str) -> Result<i64> {
254    counter
255        .try_alloc_id()
256        .map_err(|_| relate_core::Error::execution(format!("{what} ID exhausted")))
257}
258
259#[derive(Debug, Clone, Default)]
260pub struct Procedure {
261    pub name: String,
262    pub arg_names: Vec<String>,
263    /// Cypher type names (`STRING`, `INTEGER`, `NUMBER`, …) aligned with `arg_names`.
264    pub arg_types: Vec<String>,
265    pub yield_names: Vec<String>,
266    pub rows: Vec<BTreeMap<String, Value>>,
267}
268
269use chain::{Chain, Ver, VerRef};
270use id_vec::IdVec;
271
272/// The one MVCC version-chain record: node and rel chains share the shape
273/// (and, via [`cow`], the copy-on-write policy) through the aliases below.
274type NodeVer = Ver<LiveNode>;
275type RelVer = Ver<LiveRel>;
276
277pub(crate) fn node_version_stride() -> u64 {
278    std::mem::size_of::<NodeVer>() as u64
279}
280
281pub(crate) fn rel_version_stride() -> u64 {
282    std::mem::size_of::<RelVer>() as u64
283}
284
285/// The in-map size of an inline node slot: the row and its birth timestamp.
286/// One id slot, including the discriminant. The floor charges the vector
287/// of these, not a hash-map entry (ADR-0532).
288pub(crate) fn node_slot() -> u64 {
289    std::mem::size_of::<Option<Chain<LiveNode>>>() as u64
290}
291
292pub(crate) fn rel_slot() -> u64 {
293    std::mem::size_of::<Option<Chain<LiveRel>>>() as u64
294}
295
296pub(crate) fn adj_slot() -> u64 {
297    std::mem::size_of::<Option<TypedAdj>>() as u64
298}
299
300/// One sealed side-table id slot, the stride of the sealed stores' arrays.
301fn sealed_slot() -> u64 {
302    std::mem::size_of::<Option<SealedAdj>>() as u64
303}
304
305fn sealed_value() -> u64 {
306    std::mem::size_of::<SealedAdj>() as u64
307}
308
309pub(crate) fn node_value() -> u64 {
310    std::mem::size_of::<Chain<LiveNode>>() as u64
311}
312
313pub(crate) fn rel_value() -> u64 {
314    std::mem::size_of::<Chain<LiveRel>>() as u64
315}
316
317fn adj_value() -> u64 {
318    std::mem::size_of::<TypedAdj>() as u64
319}
320
321/// Copy-on-write over `id`'s slot ([`Chain::cow`]) at the write timestamp.
322fn cow<Live: Clone>(write_ts: &AtomicU64, map: &IdVec<Chain<Live>>, id: i64) -> Option<Live> {
323    let ts = write_ts.load(Ordering::Acquire);
324    map.get_mut(&id)?.cow(ts)
325}
326
327#[derive(Debug)]
328pub struct Graph {
329    /// Which fixed namespace of the store this graph is (ADR-0116 §1, §10).
330    /// The executor needs it for namespace-qualified element ids (ADR-0116
331    /// §7); `neo4j` is the default so existing construction sites are
332    /// unchanged.
333    namespace: Namespace,
334    /// Store-level services (procedure registry, LOAD CSV policy, preview
335    /// set) shared by every namespace graph of a store (ADR-0116 §10) as one
336    /// `Arc` bundle. Not a field consumers can reach: the `Arc` identity is
337    /// the one-bundle invariant, so access goes through
338    /// [`Graph::procedure`], [`Graph::has_procedure`],
339    /// [`Graph::register_procedure`], [`Graph::csv_policy`],
340    /// [`Graph::preview`], [`Graph::databases`],
341    /// [`Graph::configure_load_csv`], [`Graph::configure_preview`] and
342    /// [`Graph::share_services_from`].
343    services: Arc<StoreServices>,
344    next_node_id: AtomicI64,
345    next_rel_id: AtomicI64,
346    /// Last published commit (ADR-0012 / ADR-0013). Stored after apply (ADR-0018).
347    published_ts: AtomicU64,
348    write_ts: AtomicU64,
349    in_write: AtomicBool,
350    record_redo: AtomicBool,
351    nodes: IdVec<Chain<LiveNode>>,
352    rels: IdVec<Chain<LiveRel>>,
353    out_adj: IdVec<TypedAdj>,
354    in_adj: IdVec<TypedAdj>,
355    /// The sealed tier, one side table per direction keyed by node (ADR-0551):
356    /// a node's compressed chunks and versioned tombstones. An entry exists
357    /// only where a fold or a delete's tombstone landed, so a node that never
358    /// folds pays nothing; the delta slot stays 24 bytes.
359    sealed_out: IdVec<SealedAdj>,
360    sealed_in: IdVec<SealedAdj>,
361    /// LABS-851 (the structure round): the counting operator's count
362    /// state — per-type rel counts, (start-label, type, end-label) pair
363    /// counts, per-label live node counts, and the total live node
364    /// count — as one bundle behind one mutex (the `indexes: Indexes`
365    /// precedent), so the windowed-consistency invariant is structural:
366    /// the count-only reader holds the one guard across its exactness
367    /// check and reads, every bump takes the same guard, and a future
368    /// arm's state lands inside the bundle instead of as another
369    /// sibling lock. Per-field semantics, charges, and the bump/rebuild
370    /// discipline live with the type in `graph/count_state.rs`.
371    count_stats: Mutex<CountStats>,
372    /// LABS-351: per-(label, rel-type) out-degree histogram, log2-bucketed
373    /// (bucket k counts nodes of the label whose out-degree on the rel type
374    /// is 2^k..2^(k+1)-1). The mean degree (`rel_type_rows / label_rows`)
375    /// lies on the heavy-tailed shape where the hub join applies; the
376    /// histogram's tail is the honest degree for start-selection and
377    /// gate estimates. This is the HIGH-WATER degree, not the live one:
378    /// the typed adjacency keeps tombstoned entries (its chunk length
379    /// never shrinks), so the bucket only ever moves up on create — a
380    /// floor that can only overestimate and never miss a supernode,
381    /// which is exactly the conservative direction a gate needs. The
382    /// adjacency rebuild recomputes it from the live rels in one pass.
383    /// Estimate state the counting operator never reads — it stays
384    /// beside the count bundle, not inside it.
385    degree_histograms: Mutex<HashMap<(u32, u32), [u64; Self::DEGREE_BUCKETS]>>,
386    /// ADR-0439: the maintained, single-version per-constraint committed
387    /// tuple map (`unique`/`key` constraints, node and relationship). Unlike
388    /// the lazily built postings in [`Indexes`], this map is eagerly current;
389    /// `graph/constraint_keys/mod.rs` owns its charge family and
390    /// backfill/rebuild lifecycle; `simulation.rs` owns the op classification
391    /// and the entity simulation; `seams.rs` the `apply_redo` maintenance;
392    /// `ddl.rs` the batch DDL accumulator; `admission.rs` the commit-time
393    /// admission probe; `estimate.rs` the entry-growth estimate (one-way: the
394    /// admission and estimate sides import the map's vocabulary).
395    constraint_keys: Mutex<ConstraintKeyIndex>,
396    interner: Interner,
397    catalog: Mutex<Catalog>,
398    pub(crate) theater: Mutex<TheaterData>,
399    /// Exact old definitions whose enforcement was absent from a legacy image/WAL.
400    legacy_unenforced: Mutex<HashMap<String, ConstraintDef>>,
401    stats: Mutex<QueryStats>,
402    /// All lazily maintained index state: the label index, the equality and
403    /// declared pair maps, the interned sentinels and the committed index
404    /// memory charge — one bundle, [`Indexes`].
405    indexes: Indexes,
406    /// LABS-643: the committed epoch's memoized sampled `CONTAINS`
407    /// estimates — the plan-stats read
408    /// ([`Graph::pattern_contains_rows`](crate::Graph::pattern_contains_rows))
409    /// answers without a TEXT index by sampling, and the executor's
410    /// per-row start-selection estimate must not resample per row. See
411    /// [`ContainsMemo`] for the epoch reset and the cap.
412    contains_memo: Mutex<ContainsMemo>,
413    pending_redo: Mutex<Vec<RedoOp>>,
414    /// Source-scoped pull identity (ADR-0080).
415    pull_identity: PullIdentityIndex,
416    /// Ids mutated since the last successful checkpoint (ADR-0022).
417    dirty_nodes: Mutex<HashSet<NodeId>>,
418    dirty_rels: Mutex<HashSet<RelId>>,
419    /// In-flight snapshot pins (ADR-0038). Each slot is free / claiming / ts+1.
420    pins: Box<[AtomicU64]>,
421    pin_cursor: AtomicU64,
422    /// Live graph + index logical bytes (ADR-0042).
423    used_bytes: AtomicU64,
424}
425
426impl Default for Graph {
427    fn default() -> Self {
428        let interner = Interner::default();
429        let indexes = Indexes::new(&interner);
430        Self {
431            namespace: Namespace::Neo4j,
432            services: Arc::new(StoreServices::default()),
433            next_node_id: AtomicI64::new(0),
434            next_rel_id: AtomicI64::new(0),
435            published_ts: AtomicU64::new(0),
436            write_ts: AtomicU64::new(0),
437            in_write: AtomicBool::new(false),
438            record_redo: AtomicBool::new(true),
439            nodes: IdVec::default(),
440            rels: IdVec::default(),
441            out_adj: IdVec::default(),
442            in_adj: IdVec::default(),
443            sealed_out: IdVec::default(),
444            sealed_in: IdVec::default(),
445            count_stats: Mutex::new(CountStats::default()),
446            degree_histograms: Mutex::new(HashMap::new()),
447            constraint_keys: Mutex::new(ConstraintKeyIndex::default()),
448            interner,
449            catalog: Mutex::new(Catalog::default()),
450            theater: Mutex::new(TheaterData::default()),
451            indexes,
452            contains_memo: Mutex::new(ContainsMemo::default()),
453            legacy_unenforced: Mutex::new(HashMap::new()),
454            stats: Mutex::new(QueryStats::default()),
455            pending_redo: Mutex::new(Vec::new()),
456            pull_identity: PullIdentityIndex::default(),
457            dirty_nodes: Mutex::new(HashSet::new()),
458            dirty_rels: Mutex::new(HashSet::new()),
459            pins: (0..PIN_SLOTS).map(|_| AtomicU64::new(PIN_FREE)).collect(),
460            pin_cursor: AtomicU64::new(0),
461            used_bytes: AtomicU64::new(0),
462        }
463    }
464}
465
466/// 256 in-flight statements; excess pins retry a bounded number of times and
467/// then fail with a typed "snapshot pin" error (ADR-0038, ADR-0111).
468const PIN_SLOTS: usize = 256;
469const PIN_FREE: u64 = 0;
470const PIN_CLAIMING: u64 = u64::MAX;
471/// Bounded retry budget for a full pin table. Each retry scans all 256 slots
472/// and yields once; the budget is deliberately small so a saturated table
473/// fails in microseconds to low milliseconds rather than stalling forever
474/// (ADR-0111). The slot array and lock-free protocol are unchanged (ADR-0038).
475const PIN_ACQUIRE_RETRIES: u32 = 1024;
476
477/// Registered `snapshot_ts` until drop (ADR-0023 / ADR-0038).
478pub struct SnapshotPin<'a> {
479    graph: &'a Graph,
480    ts: u64,
481    slot: usize,
482}
483
484impl SnapshotPin<'_> {
485    pub fn ts(&self) -> u64 {
486        self.ts
487    }
488
489    /// Keep the pin after this guard is forgotten (explicit txn, ADR-0028 / ADR-0038).
490    pub fn detach(self) -> usize {
491        let slot = self.slot;
492        std::mem::forget(self);
493        slot
494    }
495}
496
497impl Drop for SnapshotPin<'_> {
498    fn drop(&mut self) {
499        self.graph.unpin_slot(self.slot);
500    }
501}
502
503fn visible(xmin: u64, xmax: u64, ts: u64) -> bool {
504    xmin != 0 && xmin <= ts && (xmax == 0 || xmax > ts)
505}
506
507fn checked_persisted_id(id: i64, what: &str) -> Result<i64> {
508    relate_core::validate_persisted_id(id, what)?;
509    Ok(id + 1)
510}
511
512fn requires_enforced_label(def: &ConstraintDef) -> bool {
513    def.kind
514        .parse::<relate_model::ConstraintType>()
515        .is_ok_and(|kind| kind.is_enforced_label_kind())
516}
517
518fn matching_enforced_label(def: &ConstraintDef, c: &relate_model::Constraint) -> bool {
519    c.label == def.label
520        && c.properties == def.properties
521        && def.kind.parse::<relate_model::ConstraintType>() == Ok(c.constraint_type)
522        && c.property_type == def.property_type
523        && c.constraint_type
524            .enforced_label_site()
525            .is_some_and(|site| site.is_relationship() == def.relationship)
526        && c.enforced_label
527            .as_deref()
528            .is_some_and(|label| !label.is_empty())
529}
530
531/// Whether a derived record names an enforced label at all: its kind
532/// requires one and the label is present and non-empty. The per-entry core
533/// both checkpoint gates share (each keeps its own error mapping).
534fn has_enforced_label(c: &relate_model::Constraint) -> bool {
535    c.constraint_type.is_enforced_label_kind()
536        && c.enforced_label
537            .as_deref()
538            .is_some_and(|label| !label.is_empty())
539}
540
541impl Graph {
542    /// Whether the committed current graph type could carry property
543    /// default values (CIP-262): the committed-theater half of the
544    /// statement boundary's scratch-aware gate
545    /// ([`ExecGraph::has_property_defaults`] answers over both
546    /// vintages). A false positive only costs one overlay read.
547    pub(crate) fn has_property_defaults(&self) -> bool {
548        let theater = self.theater.lock().expect("theater lock poisoned");
549        spec_has_property_defaults(&theater.current_graph_type)
550    }
551
552    /// Which fixed namespace of the store this graph is (ADR-0116 §1).
553    pub fn namespace(&self) -> Namespace {
554        self.namespace
555    }
556
557    /// Set the graph's namespace identity. Called by the store when it
558    /// creates or swaps a namespace slot (ADR-0116 §10); not public API.
559    #[doc(hidden)]
560    pub fn set_namespace(&mut self, namespace: Namespace) {
561        self.namespace = namespace;
562    }
563
564    pub fn commit_ts(&self) -> u64 {
565        self.published_ts.load(Ordering::Acquire)
566    }
567
568    /// Whether a base write window is in flight (`begin_write`..
569    /// `commit_write` / `apply_redo`): the maintained statistics are
570    /// already bumped for it, but the commit is not published yet — a
571    /// concurrent reader must not answer from them (the count-only
572    /// short-circuit's exactness precondition, LABS-370 v1 follow-up).
573    pub(crate) fn in_write_window(&self) -> bool {
574        self.in_write.load(Ordering::Acquire)
575    }
576
577    pub fn set_commit_ts(&self, ts: u64) {
578        self.published_ts.store(ts, Ordering::Release);
579    }
580
581    /// Live graph + index logical bytes (ADR-0042, ADR-0202).
582    pub fn used_bytes(&self) -> u64 {
583        self.used_bytes
584            .load(Ordering::Relaxed)
585            .saturating_add(self.interner.bytes())
586    }
587
588    /// Full walk of retained versions, adjacency, and the interner
589    /// (test / `rebuild_indexes` oracle).
590    pub fn accounted_bytes(&self) -> u64 {
591        self.structure_bytes().saturating_add(self.interner.bytes())
592    }
593
594    fn structure_bytes(&self) -> u64 {
595        let charge = self.index_charge();
596        let mut n = 0u64;
597        n = n.saturating_add(self.nodes.array_bytes());
598        self.nodes.for_each(|_id, vers| {
599            n = n.saturating_add(crate::memory::node_chain_bytes(vers.shape()));
600            for v in vers.iter() {
601                n = n.saturating_add(crate::memory::live_node_account_live(
602                    v.live,
603                    &self.interner,
604                    &charge,
605                ));
606            }
607        });
608        n = n.saturating_add(self.rels.array_bytes());
609        self.rels.for_each(|_id, vers| {
610            n = n.saturating_add(crate::memory::rel_chain_bytes(vers.shape()));
611            for v in vers.iter() {
612                n = n.saturating_add(crate::memory::live_rel_account_live(v.live));
613            }
614        });
615        n = n.saturating_add(self.out_adj.array_bytes());
616        n = n.saturating_add(self.in_adj.array_bytes());
617        self.out_adj
618            .for_each(|_id, adj| n = n.saturating_add(adj.floor_bytes()));
619        self.in_adj
620            .for_each(|_id, adj| n = n.saturating_add(adj.floor_bytes()));
621        // The sealed side tables (ADR-0551) are retained structure: each
622        // entry's compressed chunks and tombstones, the floor ADR-0551
623        // prices, plus the slot arrays that hold them — the term the heap
624        // census reads as `slot_bytes`.
625        n = n.saturating_add(self.sealed_out.array_bytes());
626        n = n.saturating_add(self.sealed_in.array_bytes());
627        for sealed in [&self.sealed_out, &self.sealed_in] {
628            sealed.for_each(|_id, region| n = n.saturating_add(region.floor_bytes()));
629        }
630        // LABS-351 / LABS-370: the degree histograms and the count
631        // bundle's charged maps are retained structure — the recount
632        // oracle must include them or the incremental entry charges
633        // drift from it (the #398 lesson). Each family's term lives
634        // with the family (graph/degree_stats.rs,
635        // graph/count_state.rs) and composes here, at the oracle's
636        // one site, beside the constraint-key term.
637        n = n.saturating_add(self.degree_stats_structure_bytes());
638        n = n.saturating_add(self.count_state_structure_bytes());
639        // ADR-0439: the committed constraint-key map is retained structure
640        // too; it carries the bytes each entry was charged, so the recount
641        // and the incremental charge cannot drift.
642        n = n.saturating_add(self.constraint_keys_structure_bytes());
643        n
644    }
645
646    pub fn recompute_used(&self) {
647        self.used_bytes
648            .store(self.structure_bytes(), Ordering::Relaxed);
649    }
650
651    /// Live-size delta of `ops`. Nodes are accounted under the charge in
652    /// force after `ops`; when that differs from the current charge (DDL in
653    /// the batch), every retained version — including ones `ops` tombstone —
654    /// is moved from the old charge to the new one. A delete keeps its
655    /// record until GC, so it adds nothing. A copy-on-write set adds the
656    /// new version.
657    pub fn estimate_redo_delta(&self, ops: &[RedoOp]) -> i64 {
658        self.estimate_redo_delta_with_constraint_growth(ops, None)
659            .total
660    }
661
662    /// [`Graph::estimate_redo_delta`] with the constraint-key entry-growth
663    /// term optionally supplied by the caller. The group-commit admission
664    /// loop classifies each slot once and passes the delta its walk produced,
665    /// so the slot's ops are not re-classified here (ADR-0439).
666    #[doc(hidden)]
667    pub fn estimate_redo_delta_with_constraint_growth(
668        &self,
669        ops: &[RedoOp],
670        constraint_growth: Option<i64>,
671    ) -> crate::memory::RedoDelta {
672        let before = self.index_charge();
673        let after = self.charge_after_ops(ops);
674        let crate::memory::RedoDelta {
675            total: mut delta,
676            tombstone_spill,
677        } = crate::memory::estimate_redo_delta(
678            &self.interner,
679            ops,
680            |id| self.node(id),
681            |id| self.rel_form(id),
682            |id| self.node_chain_shape(id),
683            |id| self.rel_chain_shape(id),
684            self.nodes.span(),
685            self.rels.span(),
686            &after,
687        );
688        delta += self.estimate_adj_delta(ops);
689        delta += self.estimate_intern_delta(ops);
690        // LABS-370 (security follow-up): the count family's entry growth
691        // is committed structure too — an oversized-label write must be
692        // rejected at admission, not after its entries land past the cap
693        // (graph/degree_stats.rs owns the term).
694        delta += self.estimate_stats_entry_growth(ops);
695        // ADR-0439: a constrained write's new entries are committed
696        // structure too — refused at admission, never after they land. The
697        // group path supplies the delta its admission walk already computed.
698        delta += match constraint_growth {
699            Some(growth) => growth,
700            None => self.estimate_constraint_key_entry_growth(ops),
701        };
702        if before.as_ref() != &after {
703            self.nodes.for_each(|id, vers| {
704                for v in vers.iter() {
705                    let n = v.live.to_node(id, &self.interner);
706                    delta += crate::memory::live_node_account(&n, &after) as i64
707                        - crate::memory::live_node_account(&n, &before) as i64;
708                }
709            });
710        }
711        crate::memory::RedoDelta {
712            total: delta,
713            tombstone_spill,
714        }
715    }
716
717    fn estimate_adj_delta(&self, ops: &[RedoOp]) -> i64 {
718        let mut out: HashMap<NodeId, Vec<(u32, usize)>> = HashMap::new();
719        let mut inn: HashMap<NodeId, Vec<(u32, usize)>> = HashMap::new();
720        let mut fresh_ids = FreshIds::new();
721        let mut delta = 0i64;
722        let slot = adj_slot();
723        let overflow = crate::memory::overflow_entry_bytes(adj_value());
724        let mut out_span = self.out_adj.span();
725        let mut in_span = self.in_adj.span();
726        let mut out_side = HashSet::new();
727        let mut in_side = HashSet::new();
728        for op in ops {
729            let RedoOp::CreateRel {
730                start,
731                end,
732                rel_type,
733                ..
734            } = op
735            else {
736                continue;
737            };
738            let type_id = fresh_ids.resolve(self, rel_type);
739            if !self.out_adj.contains_key(start) {
740                delta += span_growth(&mut out_span, *start, slot, overflow, &mut out_side);
741            }
742            if !self.in_adj.contains_key(end) {
743                delta += span_growth(&mut in_span, *end, slot, overflow, &mut in_side);
744            }
745            delta += bump_adj(&mut out, *start, type_id, || {
746                hop_counts(&self.out_adj, &self.sealed_out, *start)
747            });
748            delta += bump_adj(&mut inn, *end, type_id, || {
749                hop_counts(&self.in_adj, &self.sealed_in, *end)
750            });
751        }
752        // A delete of a hop in a type that never sealed records the type's
753        // first tombstone on an on-demand zero-hop region (ADR-0551), one per
754        // endpoint that does not hold one yet. The key carries the side: a
755        // self-loop's two endpoints are one node, but two side tables.
756        let mut regions: HashSet<(bool, NodeId, u32)> = HashSet::new();
757        let mut sealed_out_span = self.sealed_out.span();
758        let mut sealed_in_span = self.sealed_in.span();
759        let mut sealed_out_side = HashSet::new();
760        let mut sealed_in_side = HashSet::new();
761        let sealed_slot = sealed_slot();
762        let sealed_overflow = crate::memory::overflow_entry_bytes(sealed_value());
763        for op in ops {
764            let RedoOp::DeleteRel { id } = op else {
765                continue;
766            };
767            let Some((start, end, type_id)) = self.rels.get(id).map(|vers| {
768                // Every version of one rel id shares its endpoints and type.
769                let newest = vers.last();
770                (newest.live.start, newest.live.end, newest.live.type_id)
771            }) else {
772                continue;
773            };
774            for (incoming, node, sealed) in [
775                (false, start, &self.sealed_out),
776                (true, end, &self.sealed_in),
777            ] {
778                let region = sealed.get(&node);
779                let sealed = region
780                    .as_ref()
781                    .is_some_and(|region| region.chunk(type_id).is_some());
782                if !sealed && regions.insert((incoming, node, type_id)) {
783                    // A brand-new side-table entry also grows the slot array.
784                    if region.is_none() {
785                        let (span, side) = if incoming {
786                            (&mut sealed_in_span, &mut sealed_in_side)
787                        } else {
788                            (&mut sealed_out_span, &mut sealed_out_side)
789                        };
790                        delta += span_growth(span, node, sealed_slot, sealed_overflow, side);
791                    }
792                    delta += crate::adjacency::fresh_sealed_region_bytes() as i64;
793                }
794            }
795        }
796        delta
797    }
798
799    fn estimate_intern_delta(&self, ops: &[RedoOp]) -> i64 {
800        let mut seen = HashSet::new();
801        let mut extra = 0i64;
802        let mut consider = |s: &str| {
803            if !seen.insert(s.to_string()) {
804                return;
805            }
806            if self.interner.get_id(s).is_none() {
807                extra += crate::memory::interned_string_bytes(s.len()) as i64;
808            }
809        };
810        for op in ops {
811            match op {
812                RedoOp::CreateNode {
813                    labels, properties, ..
814                } => {
815                    for label in labels.iter() {
816                        consider(label);
817                    }
818                    for key in properties.keys() {
819                        consider(key);
820                    }
821                }
822                RedoOp::CreateRel {
823                    rel_type,
824                    properties,
825                    ..
826                } => {
827                    consider(rel_type);
828                    for key in properties.keys() {
829                        consider(key);
830                    }
831                }
832                RedoOp::SetNodeProp { key, .. }
833                | RedoOp::RemoveNodeProp { key, .. }
834                | RedoOp::SetRelProp { key, .. }
835                | RedoOp::RemoveRelProp { key, .. } => consider(key),
836                RedoOp::AddLabels { labels, .. } | RedoOp::RemoveLabels { labels, .. } => {
837                    for label in labels {
838                        consider(label);
839                    }
840                }
841                _ => {}
842            }
843        }
844        extra
845    }
846
847    fn index_charge(&self) -> Arc<crate::memory::IndexCharge> {
848        Arc::clone(&self.indexes.charge_cache.lock().unwrap())
849    }
850
851    fn refresh_index_charge(&self) {
852        let charge = {
853            let theater = self.theater.lock().unwrap();
854            Arc::new(crate::memory::IndexCharge::from_details(
855                theater.index_details.values(),
856            ))
857        };
858        *self.indexes.charge_cache.lock().unwrap() = charge;
859    }
860
861    fn charge_after_ops(&self, ops: &[RedoOp]) -> crate::memory::IndexCharge {
862        let theater = self.theater.lock().unwrap();
863        let mut details = theater.index_details.clone();
864        drop(theater);
865        crate::redo::project_index_details(&mut details, ops);
866        crate::memory::IndexCharge::from_details(details.values())
867    }
868
869    fn charge(&self, delta: i64) {
870        if delta > 0 {
871            self.used_bytes.fetch_add(delta as u64, Ordering::Relaxed);
872        } else if delta < 0 {
873            let sub = (-delta) as u64;
874            atomic_fetch_update!(self.used_bytes, Ordering::Relaxed, Ordering::Relaxed, |u| {
875                Some(u.saturating_sub(sub))
876            })
877            .ok();
878        }
879    }
880
881    fn charge_node_swap(&self, before: Option<&Node>, after: Option<&Node>) {
882        let charge = self.index_charge();
883        let b = before
884            .map(|n| crate::memory::live_node_account(n, &charge))
885            .unwrap_or(0);
886        let a = after
887            .map(|n| crate::memory::live_node_account(n, &charge))
888            .unwrap_or(0);
889        self.charge(a as i64 - b as i64);
890    }
891
892    fn charge_rel_after_edit(&self, id: RelId, before_bytes: u64, before_shape: ChainShape) {
893        let after_shape = self.rel_chain_shape(id);
894        let after_bytes = self.visible_rel_account(id);
895        if after_shape != before_shape {
896            let growth = crate::memory::rel_chain_bytes(after_shape) as i64
897                - crate::memory::rel_chain_bytes(before_shape) as i64;
898            self.charge(after_bytes as i64 + growth);
899        } else {
900            self.charge(after_bytes as i64 - before_bytes as i64);
901        }
902    }
903
904    #[cfg(test)]
905    fn node_chain_len(&self, id: NodeId) -> usize {
906        self.nodes.get(&id).map_or(0, |v| v.len())
907    }
908
909    fn node_chain_shape(&self, id: NodeId) -> ChainShape {
910        self.nodes
911            .get(&id)
912            .map_or(ChainShape::Absent, |v| v.shape())
913    }
914
915    fn rel_chain_shape(&self, id: RelId) -> ChainShape {
916        self.rels.get(&id).map_or(ChainShape::Absent, |v| v.shape())
917    }
918
919    /// Copy-on-write keeps the previous version. An in-place edit replaces it.
920    fn charge_node_after_edit(&self, id: NodeId, before: Option<&Node>, before_shape: ChainShape) {
921        let after = self.node(id);
922        let after_shape = self.node_chain_shape(id);
923        if after_shape != before_shape {
924            let charge = self.index_charge();
925            let added = after
926                .as_ref()
927                .map(|n| crate::memory::live_node_account(n, &charge))
928                .unwrap_or(0);
929            let growth = crate::memory::node_chain_bytes(after_shape) as i64
930                - crate::memory::node_chain_bytes(before_shape) as i64;
931            self.charge(added as i64 + growth);
932        } else {
933            self.charge_node_swap(before, after.as_ref());
934        }
935    }
936
937    pub fn next_node_id(&self) -> NodeId {
938        self.next_node_id.load(Ordering::Relaxed)
939    }
940
941    pub fn set_next_node_id(&self, id: NodeId) {
942        self.next_node_id.store(id, Ordering::Relaxed);
943    }
944
945    pub fn next_rel_id(&self) -> RelId {
946        self.next_rel_id.load(Ordering::Relaxed)
947    }
948
949    fn mark_node_dirty(&self, id: NodeId) {
950        self.dirty_nodes.lock().unwrap().insert(id);
951    }
952
953    fn mark_rel_dirty(&self, id: RelId) {
954        self.dirty_rels.lock().unwrap().insert(id);
955    }
956
957    /// Pin `commit_ts` so GC cannot drop versions this statement still sees.
958    ///
959    /// The slot protocol is lock-free (ADR-0038). When every slot is
960    /// occupied the wait is bounded: the array is retried a fixed number of
961    /// times and then acquisition fails with a typed
962    /// `Error::Execution("snapshot pin: …")` instead of spinning forever
963    /// (ADR-0111).
964    pub fn pin_now(&self) -> Result<SnapshotPin<'_>> {
965        self.pin_now_with_retry(std::thread::yield_now)
966    }
967
968    /// Run the callback once after each unsuccessful full-table scan.
969    fn pin_now_with_retry(&self, mut retry: impl FnMut()) -> Result<SnapshotPin<'_>> {
970        let start = self.pin_cursor.fetch_add(1, Ordering::Relaxed) as usize;
971        for _ in 0..PIN_ACQUIRE_RETRIES {
972            for i in 0..PIN_SLOTS {
973                let slot = (start + i) % PIN_SLOTS;
974                if self.pins[slot]
975                    .compare_exchange(PIN_FREE, PIN_CLAIMING, Ordering::AcqRel, Ordering::Acquire)
976                    .is_ok()
977                {
978                    let ts = self.commit_ts();
979                    self.pins[slot].store(ts.saturating_add(1), Ordering::Release);
980                    return Ok(SnapshotPin {
981                        graph: self,
982                        ts,
983                        slot,
984                    });
985                }
986            }
987            retry();
988        }
989        Err(relate_core::Error::execution(format!(
990            "snapshot pin: all {PIN_SLOTS} slots are held"
991        )))
992    }
993
994    pub fn unpin_slot(&self, slot: usize) {
995        self.pins[slot].store(PIN_FREE, Ordering::Release);
996    }
997
998    /// True while any statement or explicit transaction holds a snapshot pin.
999    pub fn snapshot_pinned(&self) -> bool {
1000        self.pins
1001            .iter()
1002            .any(|slot| slot.load(Ordering::Acquire) != PIN_FREE)
1003    }
1004
1005    /// Lowest timestamp that may still be read. Dead iff `xmax != 0 && xmax <= horizon`.
1006    pub fn gc_horizon(&self) -> u64 {
1007        let commit = self.commit_ts();
1008        let mut min_pin: Option<u64> = None;
1009        for slot in self.pins.iter() {
1010            let v = slot.load(Ordering::Acquire);
1011            if v == PIN_CLAIMING {
1012                return 0;
1013            }
1014            if v != PIN_FREE {
1015                let ts = v - 1;
1016                min_pin = Some(min_pin.map_or(ts, |m| m.min(ts)));
1017            }
1018        }
1019        min_pin.unwrap_or(commit).min(commit)
1020    }
1021
1022    pub fn set_next_rel_id(&self, id: RelId) {
1023        self.next_rel_id.store(id, Ordering::Relaxed);
1024    }
1025
1026    fn read_ts(&self) -> u64 {
1027        if self.in_write.load(Ordering::Acquire) {
1028            self.write_ts.load(Ordering::Acquire)
1029        } else {
1030            self.commit_ts()
1031        }
1032    }
1033
1034    /// Begin a write statement: versions get xmin = commit_ts+1 until publish.
1035    /// Returns `Execution` if the next timestamp is the unsupported sentinel.
1036    pub fn begin_write(&self) -> Result<()> {
1037        let ts = self
1038            .commit_ts()
1039            .checked_add(1)
1040            .filter(|ts| *ts < u64::MAX)
1041            .ok_or_else(|| relate_core::Error::execution("write timestamp exhausted"))?;
1042        self.begin_write_at(ts)
1043    }
1044
1045    /// Begin a write with an explicit txn id (ADR-0015 optimistic snapshot).
1046    /// Returns `Execution` if `write_ts` is the unsupported sentinel.
1047    pub fn begin_write_at(&self, write_ts: u64) -> Result<()> {
1048        if write_ts == u64::MAX {
1049            return Err(relate_core::Error::execution("write timestamp exhausted"));
1050        }
1051        self.in_write.store(true, Ordering::Release);
1052        self.write_ts.store(write_ts, Ordering::Release);
1053        self.pending_redo.lock().unwrap().clear();
1054        self.record_redo.store(true, Ordering::Release);
1055        self.reset_stats();
1056        Ok(())
1057    }
1058
1059    fn alloc_node_id(&self) -> Result<NodeId> {
1060        alloc_exhaustible_id(&self.next_node_id, "node")
1061    }
1062
1063    fn alloc_rel_id(&self) -> Result<RelId> {
1064        alloc_exhaustible_id(&self.next_rel_id, "relationship")
1065    }
1066
1067    pub fn pending_commit_ts(&self) -> u64 {
1068        self.write_ts.load(Ordering::Acquire)
1069    }
1070
1071    pub fn take_redo(&self) -> Vec<RedoOp> {
1072        std::mem::take(&mut *self.pending_redo.lock().unwrap())
1073    }
1074
1075    /// Publish after WAL fsync.
1076    pub fn commit_write(&self) {
1077        self.set_commit_ts(self.write_ts.load(Ordering::Acquire));
1078        self.in_write.store(false, Ordering::Release);
1079        self.pending_redo.lock().unwrap().clear();
1080    }
1081
1082    pub fn abort_write(&self) {
1083        let ts = self.write_ts.load(Ordering::Acquire);
1084        self.nodes.retain(|_, vers| vers.abort(ts));
1085        self.rels.retain(|_, vers| vers.abort(ts));
1086        self.in_write.store(false, Ordering::Release);
1087        self.pending_redo.lock().unwrap().clear();
1088        self.rebuild_adj();
1089        self.rebuild_indexes();
1090    }
1091
1092    pub fn reset_stats(&self) {
1093        *self.stats.lock().unwrap() = QueryStats::default();
1094    }
1095
1096    pub fn node_at(&self, id: NodeId, ts: u64) -> Option<Node> {
1097        self.nodes
1098            .get(&id)
1099            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_node(id, &self.interner)))
1100    }
1101
1102    /// Label-only view of a node — no property-map materialization (ADR-0033).
1103    /// Callers that only need labels avoid `node_at`, which builds the full
1104    /// property map per node (the profile-hot `CompactProps::to_map` path).
1105    pub fn node_labels_at(&self, id: NodeId, ts: u64) -> Option<Vec<String>> {
1106        self.nodes.get(&id).and_then(|vers| {
1107            visible_version(&vers, ts).map(|v| v.live.label_strings(&self.interner))
1108        })
1109    }
1110
1111    pub fn rel_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
1112        self.rels
1113            .get(&id)
1114            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_rel(id, &self.interner)))
1115    }
1116
1117    /// Endpoints only — expand / BFS must not materialize property maps (ADR-0033).
1118    pub fn rel_ends_at(&self, id: RelId, ts: u64) -> Option<(NodeId, NodeId)> {
1119        self.rels
1120            .get(&id)
1121            .and_then(|vers| visible_version(&vers, ts).map(|v| (v.live.start, v.live.end)))
1122    }
1123
1124    /// The rel's LIVE identity — its endpoints and type (round 3,
1125    /// LABS-370 F-1-2): the live version found by [`live_version`], not
1126    /// a ts-probe — the maintained-statistics paths run inside the write
1127    /// window, where a rel created earlier in the same batch is
1128    /// invisible at `commit_ts` (its xmin > commit_ts) and one deleted
1129    /// in the batch keeps a live-looking pre-delete version. The type
1130    /// rides along because a re-used rel id can come back as a different
1131    /// rel type: a live-incidence match must hold on all three axes,
1132    /// not the endpoints alone.
1133    fn rel_live_identity(&self, id: RelId) -> Option<(NodeId, NodeId, u32)> {
1134        self.rels.get(&id).and_then(|vers| {
1135            live_version(&vers).map(|v| (v.live.start, v.live.end, v.live.type_id))
1136        })
1137    }
1138
1139    pub fn node_stub_at(&self, id: NodeId, ts: u64) -> Option<Node> {
1140        self.nodes
1141            .get(&id)
1142            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id, &self.interner)))
1143    }
1144
1145    pub fn rel_stub_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
1146        self.rels
1147            .get(&id)
1148            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id)))
1149    }
1150
1151    pub fn node_prop_at(&self, id: NodeId, ts: u64, key: &str) -> Option<Value> {
1152        self.nodes.get(&id).and_then(|vers| {
1153            visible_version(&vers, ts).and_then(|v| v.live.prop(&self.interner, key))
1154        })
1155    }
1156
1157    pub fn rel_prop_at(&self, id: RelId, ts: u64, key: &str) -> Option<Value> {
1158        self.rels.get(&id).and_then(|vers| {
1159            visible_version(&vers, ts).and_then(|v| v.live.payload.get(&self.interner, key))
1160        })
1161    }
1162
1163    pub fn node_prop_keys_at(&self, id: NodeId, ts: u64) -> Vec<String> {
1164        self.nodes
1165            .get(&id)
1166            .and_then(|vers| {
1167                vers.visible_at(ts)
1168                    .map(|v| v.live.props.keys_as_strings(&self.interner))
1169            })
1170            .unwrap_or_default()
1171    }
1172
1173    pub fn rel_prop_keys_at(&self, id: RelId, ts: u64) -> Vec<String> {
1174        self.rels
1175            .get(&id)
1176            .and_then(|vers| {
1177                vers.visible_at(ts)
1178                    .map(|v| v.live.payload.keys(&self.interner))
1179            })
1180            .unwrap_or_default()
1181    }
1182
1183    pub(crate) fn rel_visible_at(&self, id: RelId, ts: u64) -> bool {
1184        self.rels
1185            .get(&id)
1186            .is_some_and(|vers| visible_version(&vers, ts).is_some())
1187    }
1188
1189    pub fn node(&self, id: NodeId) -> Option<Node> {
1190        self.node_at(id, self.read_ts())
1191    }
1192
1193    pub fn rel(&self, id: RelId) -> Option<Relationship> {
1194        self.rel_at(id, self.read_ts())
1195    }
1196
1197    /// Account of the relationship version visible at the read timestamp.
1198    /// Uses the stored `Triple` / `Other` form, not the materialized map.
1199    fn visible_rel_account(&self, id: RelId) -> u64 {
1200        let ts = self.read_ts();
1201        self.rels
1202            .get(&id)
1203            .and_then(|vers| {
1204                vers.visible_at(ts)
1205                    .map(|v| crate::memory::live_rel_account_live(v.live))
1206            })
1207            .unwrap_or(0)
1208    }
1209
1210    fn rel_form(&self, id: RelId) -> Option<crate::store::PayloadForm> {
1211        let ts = self.read_ts();
1212        self.rels.get(&id).and_then(|vers| {
1213            vers.visible_at(ts)
1214                .map(|v| v.live.payload.form(&self.interner))
1215        })
1216    }
1217
1218    pub fn node_exists(&self, id: NodeId) -> bool {
1219        self.node_visible_at(id, self.read_ts())
1220    }
1221
1222    pub fn rel_exists(&self, id: RelId) -> bool {
1223        self.rel_visible_at(id, self.read_ts())
1224    }
1225
1226    pub fn live_node_count(&self) -> usize {
1227        self.all_node_ids().len()
1228    }
1229
1230    /// True inside a write that records redo; replay (`apply_redo_inner`) does not.
1231    fn recording(&self) -> bool {
1232        self.in_write.load(Ordering::Acquire) && self.record_redo.load(Ordering::Acquire)
1233    }
1234
1235    fn push_redo(&self, op: RedoOp) {
1236        if self.recording() {
1237            self.pending_redo.lock().unwrap().push(op);
1238        }
1239    }
1240
1241    fn bump_stats(&self, f: impl FnOnce(&mut QueryStats)) {
1242        f(&mut self.stats.lock().unwrap());
1243    }
1244
1245    fn xmin_for_install(&self) -> u64 {
1246        if self.in_write.load(Ordering::Acquire) {
1247            self.write_ts.load(Ordering::Acquire)
1248        } else {
1249            let ts = self.commit_ts();
1250            if ts == 0 {
1251                self.set_commit_ts(1);
1252                1
1253            } else {
1254                ts
1255            }
1256        }
1257    }
1258
1259    pub fn named_indexes(&self) -> Vec<IndexDef> {
1260        self.catalog
1261            .lock()
1262            .unwrap()
1263            .indexes
1264            .values()
1265            .cloned()
1266            .collect()
1267    }
1268
1269    /// Capture named indexes, constraints and their SHOW metadata at one
1270    /// admission boundary. Embedded callers hold the publication read guard
1271    /// across this call and `pin_now`; direct callers must serialize with
1272    /// their own graph writers in the same way.
1273    pub fn schema_snapshot(&self) -> SchemaSnapshot {
1274        self.schema_snapshot_with_hook(|| {})
1275    }
1276
1277    fn schema_snapshot_with_hook(&self, after_catalog: impl FnOnce()) -> SchemaSnapshot {
1278        let (indexes, constraints) = {
1279            let catalog = self.catalog.lock().unwrap();
1280            (
1281                catalog.indexes.values().cloned().collect(),
1282                catalog.constraints.values().cloned().collect(),
1283            )
1284        };
1285        after_catalog();
1286        // Publication serialization makes these non-overlapping captures
1287        // (catalog above, then databases + theater in capture_show_schema)
1288        // atomic to embedded readers, without ever nesting catalog/theater
1289        // locks.
1290        let show = self.capture_show_schema();
1291        SchemaSnapshot {
1292            indexes,
1293            constraints,
1294            show,
1295        }
1296    }
1297
1298    /// The committed SHOW metadata at this instant: the store-level
1299    /// databases table plus this graph's theater, under the theater lock.
1300    pub(crate) fn capture_show_schema(&self) -> ShowSchema {
1301        ShowSchema::capture(self.databases().snapshot(), &self.theater.lock().unwrap())
1302    }
1303
1304    pub fn named_constraints(&self) -> Vec<ConstraintDef> {
1305        self.catalog
1306            .lock()
1307            .unwrap()
1308            .constraints
1309            .values()
1310            .cloned()
1311            .collect()
1312    }
1313
1314    /// Install one catalog constraint row. Restore paths only: this mutates
1315    /// the catalog WITHOUT the maintained constraint-key map (ADR-0439), so
1316    /// the caller must finish with `rebuild_indexes` / `finish_restore`,
1317    /// which builds the map from the catalog ∪ the theater's derived set.
1318    /// Calling it on a live graph would leave a uniqueness constraint the
1319    /// admission probe cannot see.
1320    pub fn install_named_constraint(&self, def: ConstraintDef) -> Result<()> {
1321        self.catalog.lock().unwrap().insert_constraint(def)
1322    }
1323
1324    pub fn named_index(&self, name: &str) -> Option<IndexDef> {
1325        self.catalog.lock().unwrap().indexes.get(name).cloned()
1326    }
1327
1328    /// By-name constraint probe, the constraint side of [`Self::named_index`].
1329    pub fn has_constraint(&self, name: &str) -> bool {
1330        self.catalog.lock().unwrap().constraints.contains_key(name)
1331    }
1332
1333    pub fn named_index_by_schema(&self, label: &str, property: &str) -> Option<IndexDef> {
1334        self.catalog
1335            .lock()
1336            .unwrap()
1337            .index_by_schema(label, property)
1338            .cloned()
1339    }
1340
1341    pub fn install_named_index(&self, def: IndexDef) -> relate_core::Result<()> {
1342        self.catalog.lock().unwrap().insert_index(def)
1343    }
1344
1345    pub fn node_value(&self, id: NodeId) -> Value {
1346        self.node(id).map(Value::from_node).unwrap_or(Value::Null)
1347    }
1348
1349    pub fn rel_value(&self, id: RelId) -> Value {
1350        self.rel(id)
1351            .map(Value::from_relationship)
1352            .unwrap_or(Value::Null)
1353    }
1354
1355    pub fn pull_identity_get(&self, source: &str, kind: PullKind, remote_id: &str) -> Option<i64> {
1356        self.pull_identity.get(source, kind, remote_id)
1357    }
1358
1359    pub fn pull_identity_put(
1360        &self,
1361        source: String,
1362        kind: PullKind,
1363        remote_id: String,
1364        local_id: i64,
1365    ) {
1366        self.pull_identity.put(source, kind, remote_id, local_id);
1367    }
1368
1369    pub fn drop_pull_identity(&self, kind: PullKind, local_id: i64) {
1370        self.pull_identity.remove(kind, local_id);
1371    }
1372}
1373/// Whether a graph-type spec could carry property default values
1374/// (CIP-262): any element type's property declares one, or any implied
1375/// label identifies another node element type (whose chain may inherit
1376/// one down). The one predicate both vintages of the statement
1377/// boundary's gate consult -- the committed theater
1378/// ([`Graph::has_property_defaults`]) and the scratch redo slice
1379/// ([`ExecGraph::has_property_defaults`]) -- so the two can never
1380/// answer the same yes/no differently.
1381pub(crate) fn spec_has_property_defaults(spec: &crate::graph_type::GraphTypeSpec) -> bool {
1382    let identifying: std::collections::BTreeSet<&str> = spec
1383        .node_types
1384        .iter()
1385        .map(|n| n.identifying_label.as_str())
1386        .collect();
1387    spec.node_types.iter().any(|n| {
1388        n.properties.iter().any(|p| p.default_value.is_some())
1389            || n.implied_labels
1390                .iter()
1391                .any(|l| identifying.contains(l.as_str()))
1392    }) || spec
1393        .edge_types
1394        .iter()
1395        .any(|e| e.properties.iter().any(|p| p.default_value.is_some()))
1396}
1397
1398fn hop_counts(map: &IdVec<TypedAdj>, sealed: &IdVec<SealedAdj>, node: NodeId) -> Vec<(u32, usize)> {
1399    map.get(&node)
1400        .map(|adj| {
1401            adj.chunk_lens(sealed.get(&node).as_deref())
1402                .map(|(type_id, delta, sealed)| (type_id, delta + sealed))
1403                .collect()
1404        })
1405        .unwrap_or_default()
1406}
1407
1408/// The admission estimates' fresh-name resolver (LABS-425, stellar round
1409/// 1): a name the interner does not know — a label or rel type the
1410/// not-yet-applied batch mints — resolves to a descending id below the
1411/// committed range, one id per distinct name. Both estimate terms
1412/// ([`Graph::estimate_adj_delta`] here,
1413/// [`Graph::estimate_stats_entry_growth`] in
1414/// graph/degree_stats_estimate.rs) resolved this ladder by hand before;
1415/// the descending-id collision invariant (fresh ids never collide with
1416/// committed ids or each other) now lives in exactly one place.
1417struct FreshIds {
1418    fresh: HashMap<String, u32>,
1419    next: u32,
1420}
1421
1422impl FreshIds {
1423    fn new() -> Self {
1424        Self {
1425            fresh: HashMap::new(),
1426            next: u32::MAX,
1427        }
1428    }
1429
1430    /// The interned id, else this batch's earlier mint, else a new
1431    /// descending id minted and memoized.
1432    fn resolve(&mut self, g: &Graph, name: &str) -> u32 {
1433        g.interner
1434            .get_id(name)
1435            .or_else(|| self.fresh.get(name).copied())
1436            .unwrap_or_else(|| {
1437                let id = self.next;
1438                self.next = self.next.saturating_sub(1);
1439                self.fresh.insert(name.to_string(), id);
1440                id
1441            })
1442    }
1443}
1444
1445/// Bytes the slot array gains when `id` extends `span`. An id the store
1446/// will not place in the array adds one side-map entry, once per id in
1447/// this batch.
1448fn span_growth(
1449    span: &mut usize,
1450    id: NodeId,
1451    slot: u64,
1452    overflow: u64,
1453    side: &mut HashSet<NodeId>,
1454) -> i64 {
1455    let Some(idx) = usize::try_from(id).ok() else {
1456        return 0;
1457    };
1458    let need = idx.saturating_add(1);
1459    if need <= *span {
1460        return 0;
1461    }
1462    let Some(after) = crate::memory::reservable_span_bytes(need, slot) else {
1463        return if side.insert(id) { overflow as i64 } else { 0 };
1464    };
1465    let before = crate::memory::id_vec_bytes(*span, slot);
1466    *span = need;
1467    after as i64 - before as i64
1468}
1469
1470/// One node's adjacency floor in one direction: the delta hop bytes plus its
1471/// sealed side-table entry's compressed chunks and tombstones.
1472fn adj_floor(map: &IdVec<TypedAdj>, sealed: &IdVec<SealedAdj>, node: NodeId) -> u64 {
1473    map.get(&node).map(|adj| adj.floor_bytes()).unwrap_or(0)
1474        + sealed.get(&node).map_or(0, |region| region.floor_bytes())
1475}
1476
1477fn bump_adj(
1478    sim: &mut HashMap<NodeId, Vec<(u32, usize)>>,
1479    node: NodeId,
1480    type_id: u32,
1481    init: impl FnOnce() -> Vec<(u32, usize)>,
1482) -> i64 {
1483    let chunks = sim.entry(node).or_insert_with(init);
1484    let before =
1485        crate::memory::adjacency_bytes(&chunks.iter().map(|(_, n)| *n).collect::<Vec<_>>());
1486    if let Some(slot) = chunks.iter_mut().find(|c| c.0 == type_id) {
1487        slot.1 += 1;
1488    } else {
1489        chunks.push((type_id, 1));
1490    }
1491    let after = crate::memory::adjacency_bytes(&chunks.iter().map(|(_, n)| *n).collect::<Vec<_>>());
1492    after as i64 - before as i64
1493}
1494impl Graph {
1495    pub fn all_rel_ids(&self) -> Vec<RelId> {
1496        self.all_rel_ids_at(self.read_ts())
1497    }
1498
1499    pub fn all_rel_ids_at(&self, ts: u64) -> Vec<RelId> {
1500        let mut ids: Vec<_> = self
1501            .rels
1502            .keys()
1503            .into_iter()
1504            .filter(|id| self.rel_visible_at(*id, ts))
1505            .collect();
1506        ids.sort();
1507        ids
1508    }
1509
1510    pub fn all_node_ids(&self) -> Vec<NodeId> {
1511        self.all_node_ids_at(self.read_ts())
1512    }
1513
1514    pub fn all_node_ids_at(&self, ts: u64) -> Vec<NodeId> {
1515        let mut ids: Vec<_> = self
1516            .nodes
1517            .keys()
1518            .into_iter()
1519            .filter(|id| self.node_visible_at(*id, ts))
1520            .collect();
1521        ids.sort();
1522        ids
1523    }
1524
1525    pub(crate) fn node_visible_at(&self, id: NodeId, ts: u64) -> bool {
1526        self.nodes
1527            .get(&id)
1528            .is_some_and(|vers| visible_version(&vers, ts).is_some())
1529    }
1530}
1531
1532#[cfg(test)]
1533mod tests;