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::{SealedAdj, TypedAdj};
use crate::group_key::GroupKey;
use crate::memory::ChainShape;
use crate::pull_identity::PullIdentityIndex;
use crate::redo::{self, PullKind, RedoOp};
use crate::store::{Interner, LiveNode, LiveRel, RelTypes};
use adjacency::{adj_insert, adj_reposition};
use constraint_keys::ConstraintKeyIndex;
use count_state::{CountDelta, CountStats};
pub(crate) use count_state::CountProbe;
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 prop_read;
mod query_stats;
mod redo_preflight;
mod rel_postings;
mod restore;
mod services;
#[cfg(feature = "research")]
pub mod sol;
#[cfg(feature = "research")]
mod research;
#[cfg(test)]
pub(crate) mod test_support;
mod theater;
pub(crate) use declared::{spatial_holds, trigram_count, 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;
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>;
fn visible_version<Live>(vers: &Chain<Live>, ts: u64) -> Option<VerRef<'_, Live>> {
vers.visible_at(ts)
}
fn live_version<Live>(vers: &Chain<Live>) -> Option<VerRef<'_, Live>> {
vers.live()
}
pub(in crate::graph) struct RelRow {
pub(in crate::graph) id: RelId,
pub(in crate::graph) start: NodeId,
pub(in crate::graph) type_id: u32,
pub(in crate::graph) end: NodeId,
pub(in crate::graph) ts: Option<i64>,
}
#[derive(Default)]
pub(in crate::graph) struct LabelCache(HashMap<NodeId, Vec<u32>>);
impl LabelCache {
pub(in crate::graph) fn ensure(&mut self, graph: &Graph, node: NodeId) {
self.0
.entry(node)
.or_insert_with(|| graph.live_label_ids(node));
}
pub(in crate::graph) fn get(&self, node: NodeId) -> &[u32] {
self.0
.get(&node)
.expect("the fold cached every endpoint's labels")
.as_slice()
}
}
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};
macro_rules! atomic_fetch_update {
($atom:expr, $set:expr, $fetch:expr, $f:expr) => {{
#[allow(
deprecated,
reason = "fetch_update renamed to try_update in 1.99; try_update needs 1.95, MSRV is 1.88"
)]
{
$atom.fetch_update($set, $fetch, $f)
}
}};
}
pub(crate) trait ExhaustibleIdCounter {
fn try_alloc_id(&self) -> std::result::Result<i64, i64>;
}
impl ExhaustibleIdCounter for AtomicI64 {
fn try_alloc_id(&self) -> std::result::Result<i64, i64> {
atomic_fetch_update!(self, Ordering::Relaxed, Ordering::Relaxed, |id| {
if (0..i64::MAX).contains(&id) {
Some(id + 1)
} else {
None
}
})
}
}
impl ExhaustibleIdCounter for AtomicU64 {
fn try_alloc_id(&self) -> std::result::Result<i64, i64> {
atomic_fetch_update!(self, Ordering::Relaxed, Ordering::Relaxed, |id| {
(id < i64::MAX as u64).then_some(id + 1)
})
.map(|id| id as i64)
.map_err(|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()
.map_err(|_| 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 chain::{Chain, Ver, VerRef};
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 {
std::mem::size_of::<Option<Chain<LiveNode>>>() as u64
}
pub(crate) fn rel_slot() -> u64 {
std::mem::size_of::<Option<Chain<LiveRel>>>() as u64
}
pub(crate) fn adj_slot() -> u64 {
std::mem::size_of::<Option<TypedAdj>>() as u64
}
fn sealed_slot() -> u64 {
std::mem::size_of::<Option<SealedAdj>>() as u64
}
fn sealed_value() -> u64 {
std::mem::size_of::<SealedAdj>() as u64
}
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,
record_redo: AtomicBool,
nodes: IdVec<Chain<LiveNode>>,
rels: IdVec<Chain<LiveRel>>,
out_adj: IdVec<TypedAdj>,
in_adj: IdVec<TypedAdj>,
sealed_out: IdVec<SealedAdj>,
sealed_in: IdVec<SealedAdj>,
count_stats: Mutex<CountStats>,
degree_histograms: Mutex<HashMap<(u32, u32), [u64; Self::DEGREE_BUCKETS]>>,
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),
record_redo: AtomicBool::new(true),
nodes: IdVec::default(),
rels: IdVec::default(),
out_adj: IdVec::default(),
in_adj: IdVec::default(),
sealed_out: IdVec::default(),
sealed_in: IdVec::default(),
count_stats: Mutex::new(CountStats::default()),
degree_histograms: Mutex::new(HashMap::new()),
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),
}
}
}
const PIN_SLOTS: usize = 256;
const PIN_FREE: u64 = 0;
const PIN_CLAIMING: u64 = u64::MAX;
const PIN_ACQUIRE_RETRIES: u32 = 1024;
pub struct SnapshotPin<'a> {
graph: &'a Graph,
ts: u64,
slot: usize,
}
impl SnapshotPin<'_> {
pub fn ts(&self) -> u64 {
self.ts
}
pub fn detach(self) -> usize {
let slot = self.slot;
std::mem::forget(self);
slot
}
}
impl Drop for SnapshotPin<'_> {
fn drop(&mut self) {
self.graph.unpin_slot(self.slot);
}
}
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())
}
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 used_bytes(&self) -> u64 {
self.used_bytes
.load(Ordering::Relaxed)
.saturating_add(self.interner.bytes())
}
pub fn accounted_bytes(&self) -> u64 {
self.structure_bytes().saturating_add(self.interner.bytes())
}
fn structure_bytes(&self) -> u64 {
let charge = self.index_charge();
let mut n = 0u64;
n = n.saturating_add(self.nodes.array_bytes());
self.nodes.for_each(|_id, vers| {
n = n.saturating_add(crate::memory::node_chain_bytes(vers.shape()));
for v in vers.iter() {
n = n.saturating_add(crate::memory::live_node_account_live(
v.live,
&self.interner,
&charge,
));
}
});
n = n.saturating_add(self.rels.array_bytes());
self.rels.for_each(|_id, vers| {
n = n.saturating_add(crate::memory::rel_chain_bytes(vers.shape()));
for v in vers.iter() {
n = n.saturating_add(crate::memory::live_rel_account_live(v.live));
}
});
n = n.saturating_add(self.out_adj.array_bytes());
n = n.saturating_add(self.in_adj.array_bytes());
self.out_adj
.for_each(|_id, adj| n = n.saturating_add(adj.floor_bytes()));
self.in_adj
.for_each(|_id, adj| n = n.saturating_add(adj.floor_bytes()));
n = n.saturating_add(self.sealed_out.array_bytes());
n = n.saturating_add(self.sealed_in.array_bytes());
for sealed in [&self.sealed_out, &self.sealed_in] {
sealed.for_each(|_id, region| n = n.saturating_add(region.floor_bytes()));
}
n = n.saturating_add(self.degree_stats_structure_bytes());
n = n.saturating_add(self.count_state_structure_bytes());
n = n.saturating_add(self.constraint_keys_structure_bytes());
n
}
pub fn recompute_used(&self) {
self.used_bytes
.store(self.structure_bytes(), Ordering::Relaxed);
}
pub fn estimate_redo_delta(&self, ops: &[RedoOp]) -> i64 {
self.estimate_redo_delta_with_constraint_growth(ops, None)
.total
}
#[doc(hidden)]
pub fn estimate_redo_delta_with_constraint_growth(
&self,
ops: &[RedoOp],
constraint_growth: Option<i64>,
) -> crate::memory::RedoDelta {
let before = self.index_charge();
let after = self.charge_after_ops(ops);
let crate::memory::RedoDelta {
total: mut delta,
tombstone_spill,
} = crate::memory::estimate_redo_delta(
&self.interner,
ops,
|id| self.node(id),
|id| self.rel_form(id),
|id| self.node_chain_shape(id),
|id| self.rel_chain_shape(id),
self.nodes.span(),
self.rels.span(),
&after,
);
delta += self.estimate_adj_delta(ops);
delta += self.estimate_intern_delta(ops);
delta += self.estimate_stats_entry_growth(ops);
delta += match constraint_growth {
Some(growth) => growth,
None => self.estimate_constraint_key_entry_growth(ops),
};
if before.as_ref() != &after {
self.nodes.for_each(|id, vers| {
for v in vers.iter() {
let n = v.live.to_node(id, &self.interner);
delta += crate::memory::live_node_account(&n, &after) as i64
- crate::memory::live_node_account(&n, &before) as i64;
}
});
}
crate::memory::RedoDelta {
total: delta,
tombstone_spill,
}
}
fn estimate_adj_delta(&self, ops: &[RedoOp]) -> i64 {
let mut out: HashMap<NodeId, Vec<(u32, usize)>> = HashMap::new();
let mut inn: HashMap<NodeId, Vec<(u32, usize)>> = HashMap::new();
let mut fresh_ids = FreshIds::new();
let mut delta = 0i64;
let slot = adj_slot();
let overflow = crate::memory::overflow_entry_bytes(adj_value());
let mut out_span = self.out_adj.span();
let mut in_span = self.in_adj.span();
let mut out_side = HashSet::new();
let mut in_side = HashSet::new();
for op in ops {
let RedoOp::CreateRel {
start,
end,
rel_type,
..
} = op
else {
continue;
};
let type_id = fresh_ids.resolve(self, rel_type);
if !self.out_adj.contains_key(start) {
delta += span_growth(&mut out_span, *start, slot, overflow, &mut out_side);
}
if !self.in_adj.contains_key(end) {
delta += span_growth(&mut in_span, *end, slot, overflow, &mut in_side);
}
delta += bump_adj(&mut out, *start, type_id, || {
hop_counts(&self.out_adj, &self.sealed_out, *start)
});
delta += bump_adj(&mut inn, *end, type_id, || {
hop_counts(&self.in_adj, &self.sealed_in, *end)
});
}
let mut regions: HashSet<(bool, NodeId, u32)> = HashSet::new();
let mut sealed_out_span = self.sealed_out.span();
let mut sealed_in_span = self.sealed_in.span();
let mut sealed_out_side = HashSet::new();
let mut sealed_in_side = HashSet::new();
let sealed_slot = sealed_slot();
let sealed_overflow = crate::memory::overflow_entry_bytes(sealed_value());
for op in ops {
let RedoOp::DeleteRel { id } = op else {
continue;
};
let Some((start, end, type_id)) = self.rels.get(id).map(|vers| {
let newest = vers.last();
(newest.live.start, newest.live.end, newest.live.type_id)
}) else {
continue;
};
for (incoming, node, sealed) in [
(false, start, &self.sealed_out),
(true, end, &self.sealed_in),
] {
let region = sealed.get(&node);
let sealed = region
.as_ref()
.is_some_and(|region| region.chunk(type_id).is_some());
if !sealed && regions.insert((incoming, node, type_id)) {
if region.is_none() {
let (span, side) = if incoming {
(&mut sealed_in_span, &mut sealed_in_side)
} else {
(&mut sealed_out_span, &mut sealed_out_side)
};
delta += span_growth(span, node, sealed_slot, sealed_overflow, side);
}
delta += crate::adjacency::fresh_sealed_region_bytes() as i64;
}
}
}
delta
}
fn estimate_intern_delta(&self, ops: &[RedoOp]) -> i64 {
let mut seen = HashSet::new();
let mut extra = 0i64;
let mut consider = |s: &str| {
if !seen.insert(s.to_string()) {
return;
}
if self.interner.get_id(s).is_none() {
extra += crate::memory::interned_string_bytes(s.len()) as i64;
}
};
for op in ops {
match op {
RedoOp::CreateNode {
labels, properties, ..
} => {
for label in labels.iter() {
consider(label);
}
for key in properties.keys() {
consider(key);
}
}
RedoOp::CreateRel {
rel_type,
properties,
..
} => {
consider(rel_type);
for key in properties.keys() {
consider(key);
}
}
RedoOp::SetNodeProp { key, .. }
| RedoOp::RemoveNodeProp { key, .. }
| RedoOp::SetRelProp { key, .. }
| RedoOp::RemoveRelProp { key, .. } => consider(key),
RedoOp::AddLabels { labels, .. } | RedoOp::RemoveLabels { labels, .. } => {
for label in labels {
consider(label);
}
}
_ => {}
}
}
extra
}
fn index_charge(&self) -> Arc<crate::memory::IndexCharge> {
Arc::clone(&self.indexes.charge_cache.lock().unwrap())
}
fn refresh_index_charge(&self) {
let charge = {
let theater = self.theater.lock().unwrap();
Arc::new(crate::memory::IndexCharge::from_details(
theater.index_details.values(),
))
};
*self.indexes.charge_cache.lock().unwrap() = charge;
}
fn charge_after_ops(&self, ops: &[RedoOp]) -> crate::memory::IndexCharge {
let theater = self.theater.lock().unwrap();
let mut details = theater.index_details.clone();
drop(theater);
crate::redo::project_index_details(&mut details, ops);
crate::memory::IndexCharge::from_details(details.values())
}
fn charge(&self, delta: i64) {
if delta > 0 {
self.used_bytes.fetch_add(delta as u64, Ordering::Relaxed);
} else if delta < 0 {
let sub = (-delta) as u64;
atomic_fetch_update!(self.used_bytes, Ordering::Relaxed, Ordering::Relaxed, |u| {
Some(u.saturating_sub(sub))
})
.ok();
}
}
fn charge_node_swap(&self, before: Option<&Node>, after: Option<&Node>) {
let charge = self.index_charge();
let b = before
.map(|n| crate::memory::live_node_account(n, &charge))
.unwrap_or(0);
let a = after
.map(|n| crate::memory::live_node_account(n, &charge))
.unwrap_or(0);
self.charge(a as i64 - b as i64);
}
fn charge_rel_after_edit(&self, id: RelId, before_bytes: u64, before_shape: ChainShape) {
let after_shape = self.rel_chain_shape(id);
let after_bytes = self.visible_rel_account(id);
if after_shape != before_shape {
let growth = crate::memory::rel_chain_bytes(after_shape) as i64
- crate::memory::rel_chain_bytes(before_shape) as i64;
self.charge(after_bytes as i64 + growth);
} else {
self.charge(after_bytes as i64 - before_bytes as i64);
}
}
#[cfg(test)]
fn node_chain_len(&self, id: NodeId) -> usize {
self.nodes.get(&id).map_or(0, |v| v.len())
}
fn node_chain_shape(&self, id: NodeId) -> ChainShape {
self.nodes
.get(&id)
.map_or(ChainShape::Absent, |v| v.shape())
}
fn rel_chain_shape(&self, id: RelId) -> ChainShape {
self.rels.get(&id).map_or(ChainShape::Absent, |v| v.shape())
}
fn charge_node_after_edit(&self, id: NodeId, before: Option<&Node>, before_shape: ChainShape) {
let after = self.node(id);
let after_shape = self.node_chain_shape(id);
if after_shape != before_shape {
let charge = self.index_charge();
let added = after
.as_ref()
.map(|n| crate::memory::live_node_account(n, &charge))
.unwrap_or(0);
let growth = crate::memory::node_chain_bytes(after_shape) as i64
- crate::memory::node_chain_bytes(before_shape) as i64;
self.charge(added as i64 + growth);
} else {
self.charge_node_swap(before, after.as_ref());
}
}
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 pin_now(&self) -> Result<SnapshotPin<'_>> {
self.pin_now_with_retry(std::thread::yield_now)
}
fn pin_now_with_retry(&self, mut retry: impl FnMut()) -> Result<SnapshotPin<'_>> {
let start = self.pin_cursor.fetch_add(1, Ordering::Relaxed) as usize;
for _ in 0..PIN_ACQUIRE_RETRIES {
for i in 0..PIN_SLOTS {
let slot = (start + i) % PIN_SLOTS;
if self.pins[slot]
.compare_exchange(PIN_FREE, PIN_CLAIMING, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
let ts = self.commit_ts();
self.pins[slot].store(ts.saturating_add(1), Ordering::Release);
return Ok(SnapshotPin {
graph: self,
ts,
slot,
});
}
}
retry();
}
Err(relate_core::Error::execution(format!(
"snapshot pin: all {PIN_SLOTS} slots are held"
)))
}
pub fn unpin_slot(&self, slot: usize) {
self.pins[slot].store(PIN_FREE, Ordering::Release);
}
pub fn snapshot_pinned(&self) -> bool {
self.pins
.iter()
.any(|slot| slot.load(Ordering::Acquire) != PIN_FREE)
}
pub fn gc_horizon(&self) -> u64 {
let commit = self.commit_ts();
let mut min_pin: Option<u64> = None;
for slot in self.pins.iter() {
let v = slot.load(Ordering::Acquire);
if v == PIN_CLAIMING {
return 0;
}
if v != PIN_FREE {
let ts = v - 1;
min_pin = Some(min_pin.map_or(ts, |m| m.min(ts)));
}
}
min_pin.unwrap_or(commit).min(commit)
}
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())
}
pub fn commit_write(&self) {
self.set_commit_ts(self.write_ts.load(Ordering::Acquire));
self.in_write.store(false, Ordering::Release);
self.pending_redo.lock().unwrap().clear();
}
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.in_write.store(false, Ordering::Release);
self.pending_redo.lock().unwrap().clear();
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| {
vers.visible_at(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| {
vers.visible_at(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| {
vers.visible_at(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| {
vers.visible_at(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 fn named_indexes(&self) -> Vec<IndexDef> {
self.catalog
.lock()
.unwrap()
.indexes
.values()
.cloned()
.collect()
}
pub fn schema_snapshot(&self) -> SchemaSnapshot {
self.schema_snapshot_with_hook(|| {})
}
fn schema_snapshot_with_hook(&self, after_catalog: impl FnOnce()) -> SchemaSnapshot {
let (indexes, constraints) = {
let catalog = self.catalog.lock().unwrap();
(
catalog.indexes.values().cloned().collect(),
catalog.constraints.values().cloned().collect(),
)
};
after_catalog();
let show = self.capture_show_schema();
SchemaSnapshot {
indexes,
constraints,
show,
}
}
pub(crate) fn capture_show_schema(&self) -> ShowSchema {
ShowSchema::capture(self.databases().snapshot(), &self.theater.lock().unwrap())
}
pub fn named_constraints(&self) -> Vec<ConstraintDef> {
self.catalog
.lock()
.unwrap()
.constraints
.values()
.cloned()
.collect()
}
pub fn install_named_constraint(&self, def: ConstraintDef) -> Result<()> {
self.catalog.lock().unwrap().insert_constraint(def)
}
pub fn named_index(&self, name: &str) -> Option<IndexDef> {
self.catalog.lock().unwrap().indexes.get(name).cloned()
}
pub fn has_constraint(&self, name: &str) -> bool {
self.catalog.lock().unwrap().constraints.contains_key(name)
}
pub fn named_index_by_schema(&self, label: &str, property: &str) -> Option<IndexDef> {
self.catalog
.lock()
.unwrap()
.index_by_schema(label, property)
.cloned()
}
pub fn install_named_index(&self, def: IndexDef) -> relate_core::Result<()> {
self.catalog.lock().unwrap().insert_index(def)
}
pub fn node_value(&self, id: NodeId) -> Value {
self.node(id).map(Value::from_node).unwrap_or(Value::Null)
}
pub fn rel_value(&self, id: RelId) -> Value {
self.rel(id)
.map(Value::from_relationship)
.unwrap_or(Value::Null)
}
pub fn pull_identity_get(&self, source: &str, kind: PullKind, remote_id: &str) -> Option<i64> {
self.pull_identity.get(source, kind, remote_id)
}
pub fn pull_identity_put(
&self,
source: String,
kind: PullKind,
remote_id: String,
local_id: i64,
) {
self.pull_identity.put(source, kind, remote_id, local_id);
}
pub fn drop_pull_identity(&self, kind: PullKind, local_id: i64) {
self.pull_identity.remove(kind, local_id);
}
}
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()))
}
fn hop_counts(map: &IdVec<TypedAdj>, sealed: &IdVec<SealedAdj>, node: NodeId) -> Vec<(u32, usize)> {
map.get(&node)
.map(|adj| {
adj.chunk_lens(sealed.get(&node).as_deref())
.map(|(type_id, delta, sealed)| (type_id, delta + sealed))
.collect()
})
.unwrap_or_default()
}
struct FreshIds {
fresh: HashMap<String, u32>,
next: u32,
}
impl FreshIds {
fn new() -> Self {
Self {
fresh: HashMap::new(),
next: u32::MAX,
}
}
fn resolve(&mut self, g: &Graph, name: &str) -> u32 {
g.interner
.get_id(name)
.or_else(|| self.fresh.get(name).copied())
.unwrap_or_else(|| {
let id = self.next;
self.next = self.next.saturating_sub(1);
self.fresh.insert(name.to_string(), id);
id
})
}
}
fn span_growth(
span: &mut usize,
id: NodeId,
slot: u64,
overflow: u64,
side: &mut HashSet<NodeId>,
) -> i64 {
let Some(idx) = usize::try_from(id).ok() else {
return 0;
};
let need = idx.saturating_add(1);
if need <= *span {
return 0;
}
let Some(after) = crate::memory::reservable_span_bytes(need, slot) else {
return if side.insert(id) { overflow as i64 } else { 0 };
};
let before = crate::memory::id_vec_bytes(*span, slot);
*span = need;
after as i64 - before as i64
}
fn adj_floor(map: &IdVec<TypedAdj>, sealed: &IdVec<SealedAdj>, node: NodeId) -> u64 {
map.get(&node).map(|adj| adj.floor_bytes()).unwrap_or(0)
+ sealed.get(&node).map_or(0, |region| region.floor_bytes())
}
fn bump_adj(
sim: &mut HashMap<NodeId, Vec<(u32, usize)>>,
node: NodeId,
type_id: u32,
init: impl FnOnce() -> Vec<(u32, usize)>,
) -> i64 {
let chunks = sim.entry(node).or_insert_with(init);
let before =
crate::memory::adjacency_bytes(&chunks.iter().map(|(_, n)| *n).collect::<Vec<_>>());
if let Some(slot) = chunks.iter_mut().find(|c| c.0 == type_id) {
slot.1 += 1;
} else {
chunks.push((type_id, 1));
}
let after = crate::memory::adjacency_bytes(&chunks.iter().map(|(_, n)| *n).collect::<Vec<_>>());
after as i64 - before as i64
}
impl Graph {
pub fn all_rel_ids(&self) -> Vec<RelId> {
self.all_rel_ids_at(self.read_ts())
}
pub fn all_rel_ids_at(&self, ts: u64) -> Vec<RelId> {
let mut ids: Vec<_> = self
.rels
.keys()
.into_iter()
.filter(|id| self.rel_visible_at(*id, ts))
.collect();
ids.sort();
ids
}
pub fn all_node_ids(&self) -> Vec<NodeId> {
self.all_node_ids_at(self.read_ts())
}
pub fn all_node_ids_at(&self, ts: u64) -> Vec<NodeId> {
let mut ids: Vec<_> = self
.nodes
.keys()
.into_iter()
.filter(|id| self.node_visible_at(*id, ts))
.collect();
ids.sort();
ids
}
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;