Skip to main content

relate_executor/graph/
mod.rs

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