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