use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use relate_catalog::{Catalog, ConstraintDef, IndexDef};
use relate_core::{Namespace, Node, NodeId, RelId, Relationship, Result, Value};
use crate::adjacency::{SealedArena, TypedAdj};
use crate::group_key::GroupKey;
use crate::memory::ChainShape;
use crate::pull_identity::PullIdentityIndex;
use crate::redo::{self, RedoOp};
use crate::store::{Interner, LiveNode, LiveRel, RelTypes};
use constraint_keys::ConstraintKeyIndex;
use count_state::{CountDelta, CountStats};
pub(crate) use count_state::{CountProbe, LabelSetCount};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum EntityId {
Node(NodeId),
Rel(RelId),
}
mod access;
mod accounting;
#[cfg(any(test, feature = "test-hooks"))]
mod build_counter;
#[cfg(test)]
pub(crate) use build_counter::BuildCounter;
mod engine_api;
mod adjacency;
mod apply_redo;
#[cfg(feature = "research")]
pub(crate) mod census;
mod chain;
mod conflict;
pub(crate) mod constraint_keys;
mod count_state;
mod declared;
mod degree_stats;
mod degree_stats_estimate;
mod degree_stats_incident;
mod derived_migration;
mod entity_mutation;
mod id_vec;
mod index;
mod index_lookup;
mod index_postings;
mod label_mutation;
mod label_probe;
mod pair_postings;
mod pin;
mod prop_read;
mod query_stats;
pub use pin::SnapshotPin;
#[cfg(test)]
use pin::PIN_ACQUIRE_RETRIES;
#[cfg(test)]
use pin::PIN_CLAIMING;
use pin::{PIN_FREE, PIN_SLOTS};
mod rebuild;
mod redo_preflight;
mod rel_postings;
mod restore;
mod schema_api;
mod services;
mod shard;
#[cfg(feature = "research")]
pub mod sol;
#[cfg(feature = "research")]
mod research;
#[cfg(test)]
pub(crate) mod test_support;
mod theater;
mod unposted;
pub(crate) use declared::{spatial_holds, trigram_count, Extremum, RangeSeek, SpatialSeek};
use declared::{GramIndex, PointIndex, RangeIndex};
#[cfg(test)]
pub(crate) use index::CONTAINS_SAMPLE_BOUND;
use index::{ContainsMemo, Indexes};
#[cfg(test)]
pub(crate) use label_probe::take_label_probe_checks;
pub(crate) use label_probe::LabelProbe;
pub use query_stats::QueryStats;
#[cfg(feature = "test-hooks")]
#[doc(hidden)]
pub use index::take_index_rebuilds;
#[cfg(feature = "test-hooks")]
#[doc(hidden)]
pub use adjacency::Side;
#[cfg(test)]
pub(crate) use adjacency::HOP_BATCH;
pub(crate) use adjacency::{HopBuf, PeerHop};
pub use relate_planner::ContainsCount;
pub(crate) use services::StoreServices;
use theater::TheaterData;
pub(crate) type CoreMap<K, V> = dashmap::DashMap<K, V, crate::hash_seed::FxBuildHasher>;
impl relate_names::TokenResolver for Graph {
fn resolve(&self, name: &str) -> relate_names::Token {
self.interner.resolve(name)
}
}
impl Graph {
pub(in crate::graph) fn live_label_ids(&self, node: NodeId) -> Vec<u32> {
self.nodes
.get(&node)
.and_then(|vers| vers.live().map(|v| v.live.labels.clone()))
.unwrap_or_default()
}
}
pub(crate) use theater::{apply_show_overlay, DatabasesCatalog, ShowSchema};
pub use theater::{CheckpointTheater, DatabaseEntry, SchemaSnapshot};
pub(crate) trait ExhaustibleIdCounter {
fn try_alloc_id(&self) -> Option<i64>;
}
impl ExhaustibleIdCounter for AtomicI64 {
fn try_alloc_id(&self) -> Option<i64> {
self.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| {
if (0..i64::MAX).contains(&id) {
Some(id + 1)
} else {
None
}
})
.ok()
}
}
impl ExhaustibleIdCounter for AtomicU64 {
fn try_alloc_id(&self) -> Option<i64> {
self.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| {
(id < i64::MAX as u64).then_some(id + 1)
})
.ok()
.map(|id| id as i64)
}
}
pub(crate) fn delete_connected_node_error() -> relate_core::Error {
relate_core::Error::execution(format!(
"{}: DeleteConnectedNode: Cannot delete node with relationships unless DETACH",
relate_error::NestedErrorClass::ConstraintVerificationFailed.as_str(),
))
}
pub(crate) fn missing_rel_endpoint_error() -> relate_core::Error {
relate_core::Error::semantic("cannot create relationship on missing node")
}
pub(crate) fn alloc_exhaustible_id(counter: &impl ExhaustibleIdCounter, what: &str) -> Result<i64> {
counter
.try_alloc_id()
.ok_or_else(|| relate_core::Error::execution(format!("{what} ID exhausted")))
}
#[derive(Debug, Clone, Default)]
pub struct Procedure {
pub name: String,
pub arg_names: Vec<String>,
pub arg_types: Vec<String>,
pub yield_names: Vec<String>,
pub rows: Vec<BTreeMap<String, Value>>,
}
use access::{live_version, visible_version};
use chain::{Chain, Ver};
use id_vec::IdVec;
type NodeVer = Ver<LiveNode>;
type RelVer = Ver<LiveRel>;
pub(crate) fn node_version_stride() -> u64 {
std::mem::size_of::<NodeVer>() as u64
}
pub(crate) fn rel_version_stride() -> u64 {
std::mem::size_of::<RelVer>() as u64
}
pub(crate) fn node_slot() -> u64 {
id_vec::slot::<Chain<LiveNode>>()
}
pub(crate) fn rel_slot() -> u64 {
id_vec::slot::<Chain<LiveRel>>()
}
pub(crate) fn adj_slot() -> u64 {
id_vec::slot::<TypedAdj>()
}
fn sealed_slot() -> u64 {
crate::adjacency::span_stride()
}
pub(crate) fn node_value() -> u64 {
std::mem::size_of::<Chain<LiveNode>>() as u64
}
pub(crate) fn rel_value() -> u64 {
std::mem::size_of::<Chain<LiveRel>>() as u64
}
fn adj_value() -> u64 {
std::mem::size_of::<TypedAdj>() as u64
}
fn cow<Live: Clone>(write_ts: &AtomicU64, map: &IdVec<Chain<Live>>, id: i64) -> Option<Live> {
let ts = write_ts.load(Ordering::Acquire);
map.get_mut(&id)?.cow(ts)
}
#[derive(Debug)]
pub struct Graph {
namespace: Namespace,
services: Arc<StoreServices>,
next_node_id: AtomicI64,
next_rel_id: AtomicI64,
published_ts: AtomicU64,
write_ts: AtomicU64,
in_write: AtomicBool,
restoring: AtomicBool,
record_redo: AtomicBool,
nodes: IdVec<Chain<LiveNode>>,
rels: IdVec<Chain<LiveRel>>,
out_adj: IdVec<TypedAdj>,
in_adj: IdVec<TypedAdj>,
sealed_out: SealedArena,
sealed_in: SealedArena,
count_stats: Mutex<CountStats>,
degree_histograms: Mutex<degree_stats::DegreeHistograms>,
constraint_keys: Mutex<ConstraintKeyIndex>,
interner: Interner,
catalog: Mutex<Catalog>,
pub(crate) theater: Mutex<TheaterData>,
legacy_unenforced: Mutex<HashMap<String, ConstraintDef>>,
stats: Mutex<QueryStats>,
indexes: Indexes,
contains_memo: Mutex<ContainsMemo>,
pending_redo: Mutex<Vec<RedoOp>>,
pull_identity: PullIdentityIndex,
dirty_nodes: Mutex<HashSet<NodeId>>,
dirty_rels: Mutex<HashSet<RelId>>,
pins: Box<[AtomicU64]>,
pin_cursor: AtomicU64,
used_bytes: AtomicU64,
}
impl Default for Graph {
fn default() -> Self {
let interner = Interner::default();
let indexes = Indexes::new(&interner);
Self {
namespace: Namespace::Neo4j,
services: Arc::new(StoreServices::default()),
next_node_id: AtomicI64::new(0),
next_rel_id: AtomicI64::new(0),
published_ts: AtomicU64::new(0),
write_ts: AtomicU64::new(0),
in_write: AtomicBool::new(false),
restoring: AtomicBool::new(true),
record_redo: AtomicBool::new(true),
nodes: IdVec::default(),
rels: IdVec::default(),
out_adj: IdVec::default(),
in_adj: IdVec::default(),
sealed_out: SealedArena::default(),
sealed_in: SealedArena::default(),
count_stats: Mutex::new(CountStats::default()),
degree_histograms: Mutex::new(degree_stats::DegreeHistograms::default()),
constraint_keys: Mutex::new(ConstraintKeyIndex::default()),
interner,
catalog: Mutex::new(Catalog::default()),
theater: Mutex::new(TheaterData::default()),
indexes,
contains_memo: Mutex::new(ContainsMemo::default()),
legacy_unenforced: Mutex::new(HashMap::new()),
stats: Mutex::new(QueryStats::default()),
pending_redo: Mutex::new(Vec::new()),
pull_identity: PullIdentityIndex::default(),
dirty_nodes: Mutex::new(HashSet::new()),
dirty_rels: Mutex::new(HashSet::new()),
pins: (0..PIN_SLOTS).map(|_| AtomicU64::new(PIN_FREE)).collect(),
pin_cursor: AtomicU64::new(0),
used_bytes: AtomicU64::new(0),
}
}
}
fn visible(xmin: u64, xmax: u64, ts: u64) -> bool {
xmin != 0 && xmin <= ts && (xmax == 0 || xmax > ts)
}
fn checked_persisted_id(id: i64, what: &str) -> Result<i64> {
relate_core::validate_persisted_id(id, what)?;
Ok(id + 1)
}
fn requires_enforced_label(def: &ConstraintDef) -> bool {
def.kind
.parse::<relate_model::ConstraintType>()
.is_ok_and(|kind| kind.is_enforced_label_kind())
}
fn matching_enforced_label(def: &ConstraintDef, c: &relate_model::Constraint) -> bool {
c.label == def.label
&& c.properties == def.properties
&& def.kind.parse::<relate_model::ConstraintType>() == Ok(c.constraint_type)
&& c.property_type == def.property_type
&& c.constraint_type
.enforced_label_site()
.is_some_and(|site| site.is_relationship() == def.relationship)
&& c.enforced_label
.as_deref()
.is_some_and(|label| !label.is_empty())
}
pub(crate) fn resolve_enforced_label(def: &mut ConstraintDef, twin_label: Option<&str>) {
if def.enforced_label.is_none() {
def.enforced_label = twin_label.map(str::to_string);
}
}
fn has_enforced_label(c: &relate_model::Constraint) -> bool {
c.constraint_type.is_enforced_label_kind()
&& c.enforced_label
.as_deref()
.is_some_and(|label| !label.is_empty())
}
impl Graph {
pub(crate) fn has_property_defaults(&self) -> bool {
let theater = self.theater.lock().expect("theater lock poisoned");
spec_has_property_defaults(&theater.current_graph_type)
}
pub fn namespace(&self) -> Namespace {
self.namespace
}
#[doc(hidden)]
pub fn set_namespace(&mut self, namespace: Namespace) {
self.namespace = namespace;
}
pub fn commit_ts(&self) -> u64 {
self.published_ts.load(Ordering::Acquire)
}
pub(crate) fn in_write_window(&self) -> bool {
self.in_write.load(Ordering::Acquire)
}
pub fn set_commit_ts(&self, ts: u64) {
self.published_ts.store(ts, Ordering::Release);
}
pub fn next_node_id(&self) -> NodeId {
self.next_node_id.load(Ordering::Relaxed)
}
pub fn set_next_node_id(&self, id: NodeId) {
self.next_node_id.store(id, Ordering::Relaxed);
}
pub fn next_rel_id(&self) -> RelId {
self.next_rel_id.load(Ordering::Relaxed)
}
fn mark_node_dirty(&self, id: NodeId) {
self.dirty_nodes.lock().unwrap().insert(id);
}
fn mark_rel_dirty(&self, id: RelId) {
self.dirty_rels.lock().unwrap().insert(id);
}
pub fn set_next_rel_id(&self, id: RelId) {
self.next_rel_id.store(id, Ordering::Relaxed);
}
fn read_ts(&self) -> u64 {
if self.in_write.load(Ordering::Acquire) {
self.write_ts.load(Ordering::Acquire)
} else {
self.commit_ts()
}
}
pub fn begin_write(&self) -> Result<()> {
let ts = self
.commit_ts()
.checked_add(1)
.filter(|ts| *ts < u64::MAX)
.ok_or_else(|| relate_core::Error::execution("write timestamp exhausted"))?;
self.begin_write_at(ts)
}
pub fn begin_write_at(&self, write_ts: u64) -> Result<()> {
if write_ts == u64::MAX {
return Err(relate_core::Error::execution("write timestamp exhausted"));
}
self.in_write.store(true, Ordering::Release);
self.write_ts.store(write_ts, Ordering::Release);
self.pending_redo.lock().unwrap().clear();
self.record_redo.store(true, Ordering::Release);
self.reset_stats();
Ok(())
}
fn alloc_node_id(&self) -> Result<NodeId> {
alloc_exhaustible_id(&self.next_node_id, "node")
}
fn alloc_rel_id(&self) -> Result<RelId> {
alloc_exhaustible_id(&self.next_rel_id, "relationship")
}
pub fn pending_commit_ts(&self) -> u64 {
self.write_ts.load(Ordering::Acquire)
}
pub fn take_redo(&self) -> Vec<RedoOp> {
std::mem::take(&mut *self.pending_redo.lock().unwrap())
}
fn end_write(&self, commit_ts: u64) {
self.set_commit_ts(commit_ts);
self.close_window();
self.close_restoring();
}
fn close_window(&self) {
self.in_write.store(false, Ordering::Release);
self.pending_redo.lock().unwrap().clear();
}
pub fn commit_write(&self) {
self.end_write(self.write_ts.load(Ordering::Acquire));
}
pub fn abort_write(&self) {
let ts = self.write_ts.load(Ordering::Acquire);
self.nodes.retain(|_, vers| vers.abort(ts));
self.rels.retain(|_, vers| vers.abort(ts));
self.close_window();
self.rebuild_adj();
self.rebuild_indexes();
}
pub fn reset_stats(&self) {
*self.stats.lock().unwrap() = QueryStats::default();
}
pub fn node_at(&self, id: NodeId, ts: u64) -> Option<Node> {
self.nodes
.get(&id)
.and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_node(id, &self.interner)))
}
pub fn node_labels_at(&self, id: NodeId, ts: u64) -> Option<Vec<String>> {
self.nodes.get(&id).and_then(|vers| {
visible_version(&vers, ts).map(|v| v.live.label_strings(&self.interner))
})
}
pub fn rel_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
self.rels
.get(&id)
.and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_rel(id, &self.interner)))
}
pub fn rel_ends_at(&self, id: RelId, ts: u64) -> Option<(NodeId, NodeId)> {
self.rels
.get(&id)
.and_then(|vers| visible_version(&vers, ts).map(|v| (v.live.start, v.live.end)))
}
fn rel_live_identity(&self, id: RelId) -> Option<(NodeId, NodeId, u32)> {
self.rels.get(&id).and_then(|vers| {
live_version(&vers).map(|v| (v.live.start, v.live.end, v.live.type_id))
})
}
pub fn node_stub_at(&self, id: NodeId, ts: u64) -> Option<Node> {
self.nodes
.get(&id)
.and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id, &self.interner)))
}
pub fn rel_stub_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
self.rels
.get(&id)
.and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id)))
}
pub fn node_prop_at(&self, id: NodeId, ts: u64, key: &str) -> Option<Value> {
self.nodes.get(&id).and_then(|vers| {
visible_version(&vers, ts).and_then(|v| v.live.prop(&self.interner, key))
})
}
pub fn rel_prop_at(&self, id: RelId, ts: u64, key: &str) -> Option<Value> {
self.rels.get(&id).and_then(|vers| {
visible_version(&vers, ts).and_then(|v| v.live.payload.get(&self.interner, key))
})
}
pub fn node_prop_keys_at(&self, id: NodeId, ts: u64) -> Vec<String> {
self.nodes
.get(&id)
.and_then(|vers| {
visible_version(&vers, ts).map(|v| v.live.props.keys_as_strings(&self.interner))
})
.unwrap_or_default()
}
pub fn rel_prop_keys_at(&self, id: RelId, ts: u64) -> Vec<String> {
self.rels
.get(&id)
.and_then(|vers| {
visible_version(&vers, ts).map(|v| v.live.payload.keys(&self.interner))
})
.unwrap_or_default()
}
pub(crate) fn rel_visible_at(&self, id: RelId, ts: u64) -> bool {
self.rels
.get(&id)
.is_some_and(|vers| visible_version(&vers, ts).is_some())
}
pub fn node(&self, id: NodeId) -> Option<Node> {
self.node_at(id, self.read_ts())
}
pub fn rel(&self, id: RelId) -> Option<Relationship> {
self.rel_at(id, self.read_ts())
}
fn visible_rel_account(&self, id: RelId) -> u64 {
let ts = self.read_ts();
self.rels
.get(&id)
.and_then(|vers| {
visible_version(&vers, ts).map(|v| crate::memory::live_rel_account_live(v.live))
})
.unwrap_or(0)
}
fn rel_form(&self, id: RelId) -> Option<crate::store::PayloadForm> {
let ts = self.read_ts();
self.rels.get(&id).and_then(|vers| {
visible_version(&vers, ts).map(|v| v.live.payload.form(&self.interner))
})
}
pub fn node_exists(&self, id: NodeId) -> bool {
self.node_visible_at(id, self.read_ts())
}
pub fn rel_exists(&self, id: RelId) -> bool {
self.rel_visible_at(id, self.read_ts())
}
pub fn live_node_count(&self) -> usize {
self.all_node_ids().len()
}
fn recording(&self) -> bool {
self.in_write.load(Ordering::Acquire) && self.record_redo.load(Ordering::Acquire)
}
fn push_redo(&self, op: RedoOp) {
if self.recording() {
self.pending_redo.lock().unwrap().push(op);
}
}
fn bump_stats(&self, f: impl FnOnce(&mut QueryStats)) {
f(&mut self.stats.lock().unwrap());
}
fn xmin_for_install(&self) -> u64 {
if self.in_write.load(Ordering::Acquire) {
self.write_ts.load(Ordering::Acquire)
} else {
let ts = self.commit_ts();
if ts == 0 {
self.set_commit_ts(1);
1
} else {
ts
}
}
}
}
pub(crate) fn spec_has_property_defaults(spec: &crate::graph_type::GraphTypeSpec) -> bool {
let identifying: std::collections::BTreeSet<&str> = spec
.node_types
.iter()
.map(|n| n.identifying_label.as_str())
.collect();
spec.node_types.iter().any(|n| {
n.properties.iter().any(|p| p.default_value.is_some())
|| n.implied_labels
.iter()
.any(|l| identifying.contains(l.as_str()))
}) || spec
.edge_types
.iter()
.any(|e| e.properties.iter().any(|p| p.default_value.is_some()))
}
impl Graph {
pub(crate) fn selects(wanted: Option<u32>, label: u32) -> bool {
wanted.is_none_or(|wanted| wanted == label)
}
pub(crate) fn selects_type(wanted: Option<&[u32]>, type_id: u32) -> bool {
wanted.is_none_or(|wanted| wanted.contains(&type_id))
}
pub(crate) fn node_visible_at(&self, id: NodeId, ts: u64) -> bool {
self.nodes
.get(&id)
.is_some_and(|vers| visible_version(&vers, ts).is_some())
}
}
#[cfg(test)]
mod tests;