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