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