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::{SealedArena, Span, 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 constraint_keys::ConstraintKeyIndex;
16use count_state::{CountDelta, CountStats};
17
18// The count-only reader's probe shape (LABS-370 round 3, F-1-5): re-exported
19// for the recognizer in `exec` — the window itself lives on `Graph`.
20pub(crate) use count_state::{CountProbe, LabelSetCount};
21
22/// `Atomic*::fetch_update` was renamed to `try_update` in Rust 1.95 and
23/// deprecated in 1.99. MSRV is 1.88, where `try_update` does not exist, so
24/// the call keeps the old name. `#[expect(deprecated)]` is wrong here: on
25/// 1.88 the lint does not fire and the build would fail.
26macro_rules! atomic_fetch_update {
27    ($atom:expr, $set:expr, $fetch:expr, $f:expr) => {{
28        #[allow(
29            deprecated,
30            reason = "fetch_update renamed to try_update in 1.99; try_update needs 1.95, MSRV is 1.88"
31        )]
32        {
33            $atom.fetch_update($set, $fetch, $f)
34        }
35    }};
36}
37
38mod accounting;
39#[cfg(any(test, feature = "test-hooks"))]
40mod build_counter;
41mod engine_api;
42
43mod adjacency;
44mod apply_redo;
45// The research-only heap-census harness (ADR-0476 quarantine shape): the
46// testing example of the same name reads it through the research feature.
47// Private module with root re-exports only (one public path per item).
48#[cfg(feature = "research")]
49pub(crate) mod census;
50mod chain;
51mod conflict;
52pub(crate) mod constraint_keys;
53mod count_state;
54mod declared;
55mod degree_stats;
56mod degree_stats_estimate;
57mod degree_stats_incident;
58mod derived_migration;
59mod entity_mutation;
60mod id_vec;
61mod index;
62mod index_lookup;
63mod index_postings;
64mod label_mutation;
65mod label_probe;
66mod pin;
67mod prop_read;
68mod query_stats;
69pub use pin::SnapshotPin;
70#[cfg(test)]
71use pin::PIN_ACQUIRE_RETRIES;
72#[cfg(test)]
73use pin::PIN_CLAIMING;
74use pin::{PIN_FREE, PIN_SLOTS};
75mod rebuild;
76mod redo_preflight;
77mod rel_postings;
78mod restore;
79mod schema_api;
80mod services;
81mod shard;
82// Research-only (speed-of-light kernels), quarantined behind the
83// non-default `research` cargo feature (ADR-0476): absent from every
84// default build and every bundle.
85#[cfg(feature = "research")]
86pub mod sol;
87// Research-only: the live-read family the sol kernel reads (the
88// helpers this quarantine used to inline in the module root; the
89// qpp half retired with its prototype, ADR-0478).
90#[cfg(feature = "research")]
91mod research;
92#[cfg(test)]
93pub(crate) mod test_support;
94mod theater;
95
96pub(crate) use declared::{spatial_holds, trigram_count, RangeSeek, SpatialSeek};
97use declared::{GramIndex, PointIndex, RangeIndex};
98#[cfg(test)]
99pub(crate) use index::CONTAINS_SAMPLE_BOUND;
100use index::{ContainsMemo, Indexes};
101// One canonical provenance type (LABS-643): defined beside the planner's
102// `PatternStats` contract that consumes it, re-exported so the executor's
103// construction sites and tests keep the one path.
104#[cfg(test)]
105pub(crate) use label_probe::take_label_probe_checks;
106pub(crate) use label_probe::LabelProbe;
107pub use query_stats::QueryStats;
108// One public path (index stays private): the whole-graph index-rebuild
109// count the facade's reopen tests read (LABS-1112's empty-replay skip).
110#[cfg(feature = "test-hooks")]
111#[doc(hidden)]
112pub use index::take_index_rebuilds;
113// The adjacency side the `test-hooks` sealed-chunk seam is read by, so the
114// storage open tests can name the direction across the crate boundary.
115#[cfg(feature = "test-hooks")]
116#[doc(hidden)]
117pub use adjacency::Side;
118pub use relate_planner::ContainsCount;
119pub(crate) use services::StoreServices;
120
121use theater::TheaterData;
122
123/// The core-store map: integer keys, FxHash — SipHash + the default
124/// hasher on dense engine-generated ids was profiled as a top-2 cost
125/// (LABS-337/LABS-358); ADR-0355's rule: a key that is attacker-writable
126/// must not use it.
127pub(crate) type CoreMap<K, V> = dashmap::DashMap<K, V, crate::hash_seed::FxBuildHasher>;
128
129/// The visible version at `ts` — the one walk every `*_at` read takes
130/// over a version chain (LABS-337's extraction of the previously
131/// five-times-spelled rev-find).
132fn visible_version<Live>(vers: &Chain<Live>, ts: u64) -> Option<VerRef<'_, Live>> {
133    vers.visible_at(ts)
134}
135
136/// The LIVE version — the last `xmax == 0` one, not a ts-probe: the
137/// maintained-statistics paths run inside the write window, where a rel
138/// created earlier in the same batch is invisible at `commit_ts` and one
139/// deleted in the batch keeps a live-looking pre-delete version. The
140/// `xmax == 0` convention is the one every live-version reader in the graph
141/// module uses (`live_label_ids`, the rebuild's live-rel scan, and the
142/// constraint_keys family's snapshots and backfills).
143fn live_version<Live>(vers: &Chain<Live>) -> Option<VerRef<'_, Live>> {
144    vers.live()
145}
146
147/// One live rel row of a wholesale adjacency build — the seam
148/// `rebuild_adj` materializes once and hands to `adjacency::adj_build`
149/// and both rebuild folds (`rebuild_degree_stats`,
150/// `rebuild_count_stats`) consume. It lives here beside [`LabelCache`],
151/// not in the adjacency-accessor sibling: the folds read it without
152/// touching adjacency. Named fields rather than a positional tuple:
153/// `start` and `end` share a type, so a swapped pair would compile and
154/// only the adjacency tests would catch it.
155pub(in crate::graph) struct RelRow {
156    pub(in crate::graph) id: RelId,
157    pub(in crate::graph) start: NodeId,
158    pub(in crate::graph) type_id: u32,
159    pub(in crate::graph) end: NodeId,
160    pub(in crate::graph) ts: Option<i64>,
161}
162
163/// The wholesale rebuild folds' shared label cache: one live-label
164/// read per distinct endpoint node ([`Graph::live_label_ids`]), the
165/// same seam [`Graph::rebuild_count_stats`] and
166/// [`Graph::rebuild_degree_stats`] both fold over — one spelling of
167/// the ensure-then-expect read, never a hand-rolled map per file.
168#[derive(Default)]
169pub(in crate::graph) struct LabelCache(HashMap<NodeId, Vec<u32>>);
170
171/// The one label-cache fill both label maps ride: `node`'s live labels
172/// read exactly once into `map`, then the entry borrowed — the
173/// cache-fill-and-borrow pattern, so no per-lookup clone of the live set
174/// rides a walk. The two maps' *read* contracts differ and stay their
175/// own: [`LabelCache::get`] is the apply fold's read-only view (its miss
176/// is an invariant break, loudly), while the stats estimate's simulated
177/// set (`BatchSim::node_labels`) is mutable — an `AddLabels` step extends
178/// it and the pair phase reads the extended set back.
179pub(in crate::graph) fn fill_labels<'m>(
180    map: &'m mut HashMap<NodeId, Vec<u32>>,
181    graph: &Graph,
182    node: NodeId,
183) -> &'m mut Vec<u32> {
184    map.entry(node)
185        .or_insert_with(|| graph.live_label_ids(node))
186}
187
188impl LabelCache {
189    /// Read `node`'s live labels into the cache exactly once, through the
190    /// one fill shape.
191    pub(in crate::graph) fn ensure(&mut self, graph: &Graph, node: NodeId) {
192        fill_labels(&mut self.0, graph, node);
193    }
194
195    /// The cached labels — the fold ensured the node's entry first, so
196    /// a miss is the fold's own invariant broken, loudly.
197    pub(in crate::graph) fn get(&self, node: NodeId) -> &[u32] {
198        self.0
199            .get(&node)
200            .expect("the fold cached every endpoint's labels")
201            .as_slice()
202    }
203}
204
205/// The store's token resolver (ADR-0541): the facade hands the graph to the
206/// planner beside its statistics, so plan-time resolution reads the same
207/// interner execution does.
208impl relate_names::TokenResolver for Graph {
209    fn resolve(&self, name: &str) -> relate_names::Token {
210        self.interner.resolve(name)
211    }
212}
213
214impl Graph {
215    /// A node's current live labels in the interned domain (u32 ids) —
216    /// the histogram's key domain, read through [`live_version`] rather than
217    /// a snapshot-visible one: the histogram is maintained at create time,
218    /// inside the writing transaction, where the just-created node is not yet
219    /// visible at `commit_ts` (the bug the first version of this read had —
220    /// every bump looped over zero labels). The `xmax == 0` convention
221    /// matches the rebuild's live-rel scan.
222    pub(in crate::graph) fn live_label_ids(&self, node: NodeId) -> Vec<u32> {
223        self.nodes
224            .get(&node)
225            .and_then(|vers| vers.live().map(|v| v.live.labels.clone()))
226            .unwrap_or_default()
227    }
228}
229
230pub(crate) use theater::{apply_show_overlay, DatabasesCatalog, ShowSchema};
231pub use theater::{CheckpointTheater, DatabaseEntry, SchemaSnapshot};
232
233/// An exhaustible `i64` id counter shared by the committed graph counters and
234/// the overlay scratch counters. Both allocate the current value and advance;
235/// both must fail rather than wrap once `i64::MAX` is reached. The two atomic
236/// widths exist because the overlay seeds its counters from the graph's.
237pub(crate) trait ExhaustibleIdCounter {
238    fn try_alloc_id(&self) -> std::result::Result<i64, i64>;
239}
240
241impl ExhaustibleIdCounter for AtomicI64 {
242    fn try_alloc_id(&self) -> std::result::Result<i64, i64> {
243        atomic_fetch_update!(self, Ordering::Relaxed, Ordering::Relaxed, |id| {
244            if (0..i64::MAX).contains(&id) {
245                Some(id + 1)
246            } else {
247                None
248            }
249        })
250    }
251}
252
253impl ExhaustibleIdCounter for AtomicU64 {
254    fn try_alloc_id(&self) -> std::result::Result<i64, i64> {
255        atomic_fetch_update!(self, Ordering::Relaxed, Ordering::Relaxed, |id| {
256            (id < i64::MAX as u64).then_some(id + 1)
257        })
258        .map(|id| id as i64)
259        .map_err(|id| id as i64)
260    }
261}
262
263/// The `DeleteConnectedNode` execution error, shared by every node-delete
264/// path so the message never drifts between them. The class token leads the
265/// payload: live Neo4j 2026.10.1 reports the
266/// `ConstraintVerificationFailed` class (G1001), and the bindings recover
267/// it through the one nested-class scan of still-stringly payloads. The
268/// token composes from the typed class vocabulary, so its spelling cannot
269/// drift from the scan's.
270pub(crate) fn delete_connected_node_error() -> relate_core::Error {
271    relate_core::Error::execution(format!(
272        "{}: DeleteConnectedNode: Cannot delete node with relationships unless DETACH",
273        relate_error::NestedErrorClass::ConstraintVerificationFailed.as_str(),
274    ))
275}
276
277/// The one typed reply for a relationship whose endpoint is not a live node:
278/// the create path's semantic error, shared by the overlay's create, the
279/// primitive's endpoint validation, and the redo preflight.
280pub(crate) fn missing_rel_endpoint_error() -> relate_core::Error {
281    relate_core::Error::semantic("cannot create relationship on missing node")
282}
283
284/// Allocate the next exhaustible id from `counter`, mapping exhaustion to the
285/// caller's `<what> ID exhausted` error.
286pub(crate) fn alloc_exhaustible_id(counter: &impl ExhaustibleIdCounter, what: &str) -> Result<i64> {
287    counter
288        .try_alloc_id()
289        .map_err(|_| relate_core::Error::execution(format!("{what} ID exhausted")))
290}
291
292#[derive(Debug, Clone, Default)]
293pub struct Procedure {
294    pub name: String,
295    pub arg_names: Vec<String>,
296    /// Cypher type names (`STRING`, `INTEGER`, `NUMBER`, …) aligned with `arg_names`.
297    pub arg_types: Vec<String>,
298    pub yield_names: Vec<String>,
299    pub rows: Vec<BTreeMap<String, Value>>,
300}
301
302use chain::{Chain, Ver, VerRef};
303use id_vec::IdVec;
304
305/// The one MVCC version-chain record: node and rel chains share the shape
306/// (and, via [`cow`], the copy-on-write policy) through the aliases below.
307type NodeVer = Ver<LiveNode>;
308type RelVer = Ver<LiveRel>;
309
310pub(crate) fn node_version_stride() -> u64 {
311    std::mem::size_of::<NodeVer>() as u64
312}
313
314pub(crate) fn rel_version_stride() -> u64 {
315    std::mem::size_of::<RelVer>() as u64
316}
317
318/// The in-map size of an inline node slot: the row and its birth timestamp.
319/// One id slot, including the discriminant. The floor charges the vector
320/// of these, not a hash-map entry (ADR-0532).
321pub(crate) fn node_slot() -> u64 {
322    std::mem::size_of::<Option<Chain<LiveNode>>>() as u64
323}
324
325pub(crate) fn rel_slot() -> u64 {
326    std::mem::size_of::<Option<Chain<LiveRel>>>() as u64
327}
328
329pub(crate) fn adj_slot() -> u64 {
330    std::mem::size_of::<Option<TypedAdj>>() as u64
331}
332
333/// One sealed span-table id slot, the stride of the sealed arena's dense
334/// span array (ADR-0599).
335fn sealed_slot() -> u64 {
336    std::mem::size_of::<Span>() as u64
337}
338
339pub(crate) fn node_value() -> u64 {
340    std::mem::size_of::<Chain<LiveNode>>() as u64
341}
342
343pub(crate) fn rel_value() -> u64 {
344    std::mem::size_of::<Chain<LiveRel>>() as u64
345}
346
347fn adj_value() -> u64 {
348    std::mem::size_of::<TypedAdj>() as u64
349}
350
351/// Copy-on-write over `id`'s slot ([`Chain::cow`]) at the write timestamp.
352fn cow<Live: Clone>(write_ts: &AtomicU64, map: &IdVec<Chain<Live>>, id: i64) -> Option<Live> {
353    let ts = write_ts.load(Ordering::Acquire);
354    map.get_mut(&id)?.cow(ts)
355}
356
357#[derive(Debug)]
358pub struct Graph {
359    /// Which fixed namespace of the store this graph is (ADR-0116 §1, §10).
360    /// The executor needs it for namespace-qualified element ids (ADR-0116
361    /// §7); `neo4j` is the default so existing construction sites are
362    /// unchanged.
363    namespace: Namespace,
364    /// Store-level services (procedure registry, LOAD CSV policy, preview
365    /// set) shared by every namespace graph of a store (ADR-0116 §10) as one
366    /// `Arc` bundle. Not a field consumers can reach: the `Arc` identity is
367    /// the one-bundle invariant, so access goes through
368    /// [`Graph::procedure`], [`Graph::has_procedure`],
369    /// [`Graph::register_procedure`], [`Graph::csv_policy`],
370    /// [`Graph::preview`], [`Graph::databases`],
371    /// [`Graph::configure_load_csv`], [`Graph::configure_preview`] and
372    /// [`Graph::share_services_from`].
373    services: Arc<StoreServices>,
374    next_node_id: AtomicI64,
375    next_rel_id: AtomicI64,
376    /// Last published commit (ADR-0012 / ADR-0013). Stored after apply (ADR-0018).
377    published_ts: AtomicU64,
378    write_ts: AtomicU64,
379    in_write: AtomicBool,
380    record_redo: AtomicBool,
381    nodes: IdVec<Chain<LiveNode>>,
382    rels: IdVec<Chain<LiveRel>>,
383    out_adj: IdVec<TypedAdj>,
384    in_adj: IdVec<TypedAdj>,
385    /// The sealed tier, one graph-level node-major arena per direction
386    /// (ADR-0551 / ADR-0599): a node's compressed chunks and versioned
387    /// tombstones. An entry exists only where a fold or a delete's tombstone
388    /// landed, so a node that never folds pays nothing; the delta slot stays
389    /// 24 bytes.
390    sealed_out: SealedArena,
391    sealed_in: SealedArena,
392    /// LABS-851 (the structure round): the counting operator's count
393    /// state — per-type rel counts, (start-label, type, end-label) pair
394    /// counts, per-label live node counts, and the total live node
395    /// count — as one bundle behind one mutex (the `indexes: Indexes`
396    /// precedent), so the windowed-consistency invariant is structural:
397    /// the count-only reader holds the one guard across its exactness
398    /// check and reads, every bump takes the same guard, and a future
399    /// arm's state lands inside the bundle instead of as another
400    /// sibling lock. Per-field semantics, charges, and the bump/rebuild
401    /// discipline live with the type in `graph/count_state.rs`.
402    count_stats: Mutex<CountStats>,
403    /// LABS-351: per-(label, rel-type) out-degree histogram, log2-bucketed
404    /// (bucket k counts nodes of the label whose out-degree on the rel type
405    /// is 2^k..2^(k+1)-1). The mean degree (`rel_type_rows / label_rows`)
406    /// lies on the heavy-tailed shape where the hub join applies; the
407    /// histogram's tail is the honest degree for start-selection and
408    /// gate estimates. This is the HIGH-WATER degree, not the live one:
409    /// the typed adjacency keeps tombstoned entries (its chunk length
410    /// never shrinks), so the bucket only ever moves up on create — a
411    /// floor that can only overestimate and never miss a supernode,
412    /// which is exactly the conservative direction a gate needs. The
413    /// adjacency rebuild recomputes it from the live rels in one pass.
414    /// Estimate state the counting operator never reads — it stays
415    /// beside the count bundle, not inside it.
416    degree_histograms: Mutex<degree_stats::DegreeHistograms>,
417    /// ADR-0439: the maintained, single-version per-constraint committed
418    /// tuple map (`unique`/`key` constraints, node and relationship). Unlike
419    /// the lazily built postings in [`Indexes`], this map is eagerly current;
420    /// `graph/constraint_keys/mod.rs` owns its charge family and
421    /// backfill/rebuild lifecycle; `simulation.rs` owns the op classification
422    /// and the entity simulation; `seams.rs` the `apply_redo` maintenance;
423    /// `ddl.rs` the batch DDL accumulator; `admission.rs` the commit-time
424    /// admission probe; `estimate.rs` the entry-growth estimate (one-way: the
425    /// admission and estimate sides import the map's vocabulary).
426    constraint_keys: Mutex<ConstraintKeyIndex>,
427    interner: Interner,
428    catalog: Mutex<Catalog>,
429    pub(crate) theater: Mutex<TheaterData>,
430    /// Exact old definitions whose enforcement was absent from a legacy image/WAL.
431    legacy_unenforced: Mutex<HashMap<String, ConstraintDef>>,
432    stats: Mutex<QueryStats>,
433    /// All lazily maintained index state: the label index, the equality and
434    /// declared pair maps, the interned sentinels and the committed index
435    /// memory charge — one bundle, [`Indexes`].
436    indexes: Indexes,
437    /// LABS-643: the committed epoch's memoized sampled `CONTAINS`
438    /// estimates — the plan-stats read
439    /// ([`Graph::pattern_contains_rows`](crate::Graph::pattern_contains_rows))
440    /// answers without a TEXT index by sampling, and the executor's
441    /// per-row start-selection estimate must not resample per row. See
442    /// [`ContainsMemo`] for the epoch reset and the cap.
443    contains_memo: Mutex<ContainsMemo>,
444    pending_redo: Mutex<Vec<RedoOp>>,
445    /// Source-scoped pull identity (ADR-0080).
446    pull_identity: PullIdentityIndex,
447    /// Ids mutated since the last successful checkpoint (ADR-0022).
448    dirty_nodes: Mutex<HashSet<NodeId>>,
449    dirty_rels: Mutex<HashSet<RelId>>,
450    /// In-flight snapshot pins (ADR-0038). Each slot is free / claiming / ts+1.
451    pins: Box<[AtomicU64]>,
452    pin_cursor: AtomicU64,
453    /// Live graph + index logical bytes (ADR-0042).
454    used_bytes: AtomicU64,
455}
456
457impl Default for Graph {
458    fn default() -> Self {
459        let interner = Interner::default();
460        let indexes = Indexes::new(&interner);
461        Self {
462            namespace: Namespace::Neo4j,
463            services: Arc::new(StoreServices::default()),
464            next_node_id: AtomicI64::new(0),
465            next_rel_id: AtomicI64::new(0),
466            published_ts: AtomicU64::new(0),
467            write_ts: AtomicU64::new(0),
468            in_write: AtomicBool::new(false),
469            record_redo: AtomicBool::new(true),
470            nodes: IdVec::default(),
471            rels: IdVec::default(),
472            out_adj: IdVec::default(),
473            in_adj: IdVec::default(),
474            sealed_out: SealedArena::default(),
475            sealed_in: SealedArena::default(),
476            count_stats: Mutex::new(CountStats::default()),
477            degree_histograms: Mutex::new(degree_stats::DegreeHistograms::default()),
478            constraint_keys: Mutex::new(ConstraintKeyIndex::default()),
479            interner,
480            catalog: Mutex::new(Catalog::default()),
481            theater: Mutex::new(TheaterData::default()),
482            indexes,
483            contains_memo: Mutex::new(ContainsMemo::default()),
484            legacy_unenforced: Mutex::new(HashMap::new()),
485            stats: Mutex::new(QueryStats::default()),
486            pending_redo: Mutex::new(Vec::new()),
487            pull_identity: PullIdentityIndex::default(),
488            dirty_nodes: Mutex::new(HashSet::new()),
489            dirty_rels: Mutex::new(HashSet::new()),
490            pins: (0..PIN_SLOTS).map(|_| AtomicU64::new(PIN_FREE)).collect(),
491            pin_cursor: AtomicU64::new(0),
492            used_bytes: AtomicU64::new(0),
493        }
494    }
495}
496
497fn visible(xmin: u64, xmax: u64, ts: u64) -> bool {
498    xmin != 0 && xmin <= ts && (xmax == 0 || xmax > ts)
499}
500
501fn checked_persisted_id(id: i64, what: &str) -> Result<i64> {
502    relate_core::validate_persisted_id(id, what)?;
503    Ok(id + 1)
504}
505
506fn requires_enforced_label(def: &ConstraintDef) -> bool {
507    def.kind
508        .parse::<relate_model::ConstraintType>()
509        .is_ok_and(|kind| kind.is_enforced_label_kind())
510}
511
512fn matching_enforced_label(def: &ConstraintDef, c: &relate_model::Constraint) -> bool {
513    c.label == def.label
514        && c.properties == def.properties
515        && def.kind.parse::<relate_model::ConstraintType>() == Ok(c.constraint_type)
516        && c.property_type == def.property_type
517        && c.constraint_type
518            .enforced_label_site()
519            .is_some_and(|site| site.is_relationship() == def.relationship)
520        && c.enforced_label
521            .as_deref()
522            .is_some_and(|label| !label.is_empty())
523}
524
525/// Whether a derived record names an enforced label at all: its kind
526/// requires one and the label is present and non-empty. The per-entry core
527/// both checkpoint gates share (each keeps its own error mapping).
528fn has_enforced_label(c: &relate_model::Constraint) -> bool {
529    c.constraint_type.is_enforced_label_kind()
530        && c.enforced_label
531            .as_deref()
532            .is_some_and(|label| !label.is_empty())
533}
534
535impl Graph {
536    /// Whether the committed current graph type could carry property
537    /// default values (CIP-262): the committed-theater half of the
538    /// statement boundary's scratch-aware gate
539    /// ([`ExecGraph::has_property_defaults`] answers over both
540    /// vintages). A false positive only costs one overlay read.
541    pub(crate) fn has_property_defaults(&self) -> bool {
542        let theater = self.theater.lock().expect("theater lock poisoned");
543        spec_has_property_defaults(&theater.current_graph_type)
544    }
545
546    /// Which fixed namespace of the store this graph is (ADR-0116 §1).
547    pub fn namespace(&self) -> Namespace {
548        self.namespace
549    }
550
551    /// Set the graph's namespace identity. Called by the store when it
552    /// creates or swaps a namespace slot (ADR-0116 §10); not public API.
553    #[doc(hidden)]
554    pub fn set_namespace(&mut self, namespace: Namespace) {
555        self.namespace = namespace;
556    }
557
558    pub fn commit_ts(&self) -> u64 {
559        self.published_ts.load(Ordering::Acquire)
560    }
561
562    /// Whether a base write window is in flight (`begin_write`..
563    /// `commit_write` / `apply_redo`): the maintained statistics are
564    /// already bumped for it, but the commit is not published yet — a
565    /// concurrent reader must not answer from them (the count-only
566    /// short-circuit's exactness precondition, LABS-370 v1 follow-up).
567    pub(crate) fn in_write_window(&self) -> bool {
568        self.in_write.load(Ordering::Acquire)
569    }
570
571    pub fn set_commit_ts(&self, ts: u64) {
572        self.published_ts.store(ts, Ordering::Release);
573    }
574
575    pub fn next_node_id(&self) -> NodeId {
576        self.next_node_id.load(Ordering::Relaxed)
577    }
578
579    pub fn set_next_node_id(&self, id: NodeId) {
580        self.next_node_id.store(id, Ordering::Relaxed);
581    }
582
583    pub fn next_rel_id(&self) -> RelId {
584        self.next_rel_id.load(Ordering::Relaxed)
585    }
586
587    fn mark_node_dirty(&self, id: NodeId) {
588        self.dirty_nodes.lock().unwrap().insert(id);
589    }
590
591    fn mark_rel_dirty(&self, id: RelId) {
592        self.dirty_rels.lock().unwrap().insert(id);
593    }
594
595    pub fn set_next_rel_id(&self, id: RelId) {
596        self.next_rel_id.store(id, Ordering::Relaxed);
597    }
598
599    fn read_ts(&self) -> u64 {
600        if self.in_write.load(Ordering::Acquire) {
601            self.write_ts.load(Ordering::Acquire)
602        } else {
603            self.commit_ts()
604        }
605    }
606
607    /// Begin a write statement: versions get xmin = commit_ts+1 until publish.
608    /// Returns `Execution` if the next timestamp is the unsupported sentinel.
609    pub fn begin_write(&self) -> Result<()> {
610        let ts = self
611            .commit_ts()
612            .checked_add(1)
613            .filter(|ts| *ts < u64::MAX)
614            .ok_or_else(|| relate_core::Error::execution("write timestamp exhausted"))?;
615        self.begin_write_at(ts)
616    }
617
618    /// Begin a write with an explicit txn id (ADR-0015 optimistic snapshot).
619    /// Returns `Execution` if `write_ts` is the unsupported sentinel.
620    pub fn begin_write_at(&self, write_ts: u64) -> Result<()> {
621        if write_ts == u64::MAX {
622            return Err(relate_core::Error::execution("write timestamp exhausted"));
623        }
624        self.in_write.store(true, Ordering::Release);
625        self.write_ts.store(write_ts, Ordering::Release);
626        self.pending_redo.lock().unwrap().clear();
627        self.record_redo.store(true, Ordering::Release);
628        self.reset_stats();
629        Ok(())
630    }
631
632    fn alloc_node_id(&self) -> Result<NodeId> {
633        alloc_exhaustible_id(&self.next_node_id, "node")
634    }
635
636    fn alloc_rel_id(&self) -> Result<RelId> {
637        alloc_exhaustible_id(&self.next_rel_id, "relationship")
638    }
639
640    pub fn pending_commit_ts(&self) -> u64 {
641        self.write_ts.load(Ordering::Acquire)
642    }
643
644    pub fn take_redo(&self) -> Vec<RedoOp> {
645        std::mem::take(&mut *self.pending_redo.lock().unwrap())
646    }
647
648    /// Publish after WAL fsync.
649    pub fn commit_write(&self) {
650        self.set_commit_ts(self.write_ts.load(Ordering::Acquire));
651        self.in_write.store(false, Ordering::Release);
652        self.pending_redo.lock().unwrap().clear();
653    }
654
655    pub fn abort_write(&self) {
656        let ts = self.write_ts.load(Ordering::Acquire);
657        self.nodes.retain(|_, vers| vers.abort(ts));
658        self.rels.retain(|_, vers| vers.abort(ts));
659        self.in_write.store(false, Ordering::Release);
660        self.pending_redo.lock().unwrap().clear();
661        self.rebuild_adj();
662        self.rebuild_indexes();
663    }
664
665    pub fn reset_stats(&self) {
666        *self.stats.lock().unwrap() = QueryStats::default();
667    }
668
669    pub fn node_at(&self, id: NodeId, ts: u64) -> Option<Node> {
670        self.nodes
671            .get(&id)
672            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_node(id, &self.interner)))
673    }
674
675    /// Label-only view of a node — no property-map materialization (ADR-0033).
676    /// Callers that only need labels avoid `node_at`, which builds the full
677    /// property map per node (the profile-hot `CompactProps::to_map` path).
678    pub fn node_labels_at(&self, id: NodeId, ts: u64) -> Option<Vec<String>> {
679        self.nodes.get(&id).and_then(|vers| {
680            visible_version(&vers, ts).map(|v| v.live.label_strings(&self.interner))
681        })
682    }
683
684    pub fn rel_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
685        self.rels
686            .get(&id)
687            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_rel(id, &self.interner)))
688    }
689
690    /// Endpoints only — expand / BFS must not materialize property maps (ADR-0033).
691    pub fn rel_ends_at(&self, id: RelId, ts: u64) -> Option<(NodeId, NodeId)> {
692        self.rels
693            .get(&id)
694            .and_then(|vers| visible_version(&vers, ts).map(|v| (v.live.start, v.live.end)))
695    }
696
697    /// The rel's LIVE identity — its endpoints and type (round 3,
698    /// LABS-370 F-1-2): the live version found by [`live_version`], not
699    /// a ts-probe — the maintained-statistics paths run inside the write
700    /// window, where a rel created earlier in the same batch is
701    /// invisible at `commit_ts` (its xmin > commit_ts) and one deleted
702    /// in the batch keeps a live-looking pre-delete version. The type
703    /// rides along because a re-used rel id can come back as a different
704    /// rel type: a live-incidence match must hold on all three axes,
705    /// not the endpoints alone.
706    fn rel_live_identity(&self, id: RelId) -> Option<(NodeId, NodeId, u32)> {
707        self.rels.get(&id).and_then(|vers| {
708            live_version(&vers).map(|v| (v.live.start, v.live.end, v.live.type_id))
709        })
710    }
711
712    pub fn node_stub_at(&self, id: NodeId, ts: u64) -> Option<Node> {
713        self.nodes
714            .get(&id)
715            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id, &self.interner)))
716    }
717
718    pub fn rel_stub_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
719        self.rels
720            .get(&id)
721            .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id)))
722    }
723
724    pub fn node_prop_at(&self, id: NodeId, ts: u64, key: &str) -> Option<Value> {
725        self.nodes.get(&id).and_then(|vers| {
726            visible_version(&vers, ts).and_then(|v| v.live.prop(&self.interner, key))
727        })
728    }
729
730    pub fn rel_prop_at(&self, id: RelId, ts: u64, key: &str) -> Option<Value> {
731        self.rels.get(&id).and_then(|vers| {
732            visible_version(&vers, ts).and_then(|v| v.live.payload.get(&self.interner, key))
733        })
734    }
735
736    pub fn node_prop_keys_at(&self, id: NodeId, ts: u64) -> Vec<String> {
737        self.nodes
738            .get(&id)
739            .and_then(|vers| {
740                vers.visible_at(ts)
741                    .map(|v| v.live.props.keys_as_strings(&self.interner))
742            })
743            .unwrap_or_default()
744    }
745
746    pub fn rel_prop_keys_at(&self, id: RelId, ts: u64) -> Vec<String> {
747        self.rels
748            .get(&id)
749            .and_then(|vers| {
750                vers.visible_at(ts)
751                    .map(|v| v.live.payload.keys(&self.interner))
752            })
753            .unwrap_or_default()
754    }
755
756    pub(crate) fn rel_visible_at(&self, id: RelId, ts: u64) -> bool {
757        self.rels
758            .get(&id)
759            .is_some_and(|vers| visible_version(&vers, ts).is_some())
760    }
761
762    pub fn node(&self, id: NodeId) -> Option<Node> {
763        self.node_at(id, self.read_ts())
764    }
765
766    pub fn rel(&self, id: RelId) -> Option<Relationship> {
767        self.rel_at(id, self.read_ts())
768    }
769
770    /// Account of the relationship version visible at the read timestamp.
771    /// Uses the stored `Triple` / `Other` form, not the materialized map.
772    fn visible_rel_account(&self, id: RelId) -> u64 {
773        let ts = self.read_ts();
774        self.rels
775            .get(&id)
776            .and_then(|vers| {
777                vers.visible_at(ts)
778                    .map(|v| crate::memory::live_rel_account_live(v.live))
779            })
780            .unwrap_or(0)
781    }
782
783    fn rel_form(&self, id: RelId) -> Option<crate::store::PayloadForm> {
784        let ts = self.read_ts();
785        self.rels.get(&id).and_then(|vers| {
786            vers.visible_at(ts)
787                .map(|v| v.live.payload.form(&self.interner))
788        })
789    }
790
791    pub fn node_exists(&self, id: NodeId) -> bool {
792        self.node_visible_at(id, self.read_ts())
793    }
794
795    pub fn rel_exists(&self, id: RelId) -> bool {
796        self.rel_visible_at(id, self.read_ts())
797    }
798
799    pub fn live_node_count(&self) -> usize {
800        self.all_node_ids().len()
801    }
802
803    /// True inside a write that records redo; replay (`apply_redo_inner`) does not.
804    fn recording(&self) -> bool {
805        self.in_write.load(Ordering::Acquire) && self.record_redo.load(Ordering::Acquire)
806    }
807
808    fn push_redo(&self, op: RedoOp) {
809        if self.recording() {
810            self.pending_redo.lock().unwrap().push(op);
811        }
812    }
813
814    fn bump_stats(&self, f: impl FnOnce(&mut QueryStats)) {
815        f(&mut self.stats.lock().unwrap());
816    }
817
818    fn xmin_for_install(&self) -> u64 {
819        if self.in_write.load(Ordering::Acquire) {
820            self.write_ts.load(Ordering::Acquire)
821        } else {
822            let ts = self.commit_ts();
823            if ts == 0 {
824                self.set_commit_ts(1);
825                1
826            } else {
827                ts
828            }
829        }
830    }
831
832    pub fn node_value(&self, id: NodeId) -> Value {
833        self.node(id).map(Value::from_node).unwrap_or(Value::Null)
834    }
835
836    pub fn rel_value(&self, id: RelId) -> Value {
837        self.rel(id)
838            .map(Value::from_relationship)
839            .unwrap_or(Value::Null)
840    }
841
842    pub fn pull_identity_get(&self, source: &str, kind: PullKind, remote_id: &str) -> Option<i64> {
843        self.pull_identity.get(source, kind, remote_id)
844    }
845
846    pub fn pull_identity_put(
847        &self,
848        source: String,
849        kind: PullKind,
850        remote_id: String,
851        local_id: i64,
852    ) {
853        self.pull_identity.put(source, kind, remote_id, local_id);
854    }
855
856    pub fn drop_pull_identity(&self, kind: PullKind, local_id: i64) {
857        self.pull_identity.remove(kind, local_id);
858    }
859}
860/// Whether a graph-type spec could carry property default values
861/// (CIP-262): any element type's property declares one, or any implied
862/// label identifies another node element type (whose chain may inherit
863/// one down). The one predicate both vintages of the statement
864/// boundary's gate consult -- the committed theater
865/// ([`Graph::has_property_defaults`]) and the scratch redo slice
866/// ([`ExecGraph::has_property_defaults`]) -- so the two can never
867/// answer the same yes/no differently.
868pub(crate) fn spec_has_property_defaults(spec: &crate::graph_type::GraphTypeSpec) -> bool {
869    let identifying: std::collections::BTreeSet<&str> = spec
870        .node_types
871        .iter()
872        .map(|n| n.identifying_label.as_str())
873        .collect();
874    spec.node_types.iter().any(|n| {
875        n.properties.iter().any(|p| p.default_value.is_some())
876            || n.implied_labels
877                .iter()
878                .any(|l| identifying.contains(l.as_str()))
879    }) || spec
880        .edge_types
881        .iter()
882        .any(|e| e.properties.iter().any(|p| p.default_value.is_some()))
883}
884
885impl Graph {
886    /// The one label-selection policy of the degree and count statistics families:
887    /// `None` selects every label, `Some(wanted)` exactly that one.
888    pub(crate) fn selects(wanted: Option<u32>, label: u32) -> bool {
889        wanted.is_none_or(|wanted| wanted == label)
890    }
891
892    /// The one type-selection policy of the degree and count statistics families:
893    /// `None` selects every type, `Some(wanted)` the listed ids.
894    pub(crate) fn selects_type(wanted: Option<&[u32]>, type_id: u32) -> bool {
895        wanted.is_none_or(|wanted| wanted.contains(&type_id))
896    }
897
898    pub fn all_rel_ids(&self) -> Vec<RelId> {
899        self.all_rel_ids_at(self.read_ts())
900    }
901
902    pub fn all_rel_ids_at(&self, ts: u64) -> Vec<RelId> {
903        let mut ids: Vec<_> = self
904            .rels
905            .keys()
906            .into_iter()
907            .filter(|id| self.rel_visible_at(*id, ts))
908            .collect();
909        ids.sort();
910        ids
911    }
912
913    pub fn all_node_ids(&self) -> Vec<NodeId> {
914        self.all_node_ids_at(self.read_ts())
915    }
916
917    pub fn all_node_ids_at(&self, ts: u64) -> Vec<NodeId> {
918        let mut ids: Vec<_> = self
919            .nodes
920            .keys()
921            .into_iter()
922            .filter(|id| self.node_visible_at(*id, ts))
923            .collect();
924        ids.sort();
925        ids
926    }
927
928    pub(crate) fn node_visible_at(&self, id: NodeId, ts: u64) -> bool {
929        self.nodes
930            .get(&id)
931            .is_some_and(|vers| visible_version(&vers, ts).is_some())
932    }
933}
934
935#[cfg(test)]
936mod tests;