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::{SealedAdj, TypedAdj};
9use crate::group_key::GroupKey;
10use crate::memory::ChainShape;
11use crate::pull_identity::PullIdentityIndex;
12use crate::redo::{self, PullKind, RedoOp};
13use crate::store::{Interner, LiveNode, LiveRel, RelTypes};
14
15use adjacency::{adj_insert, adj_reposition};
16use constraint_keys::ConstraintKeyIndex;
17use count_state::{CountDelta, CountStats};
18
19pub(crate) use count_state::CountProbe;
22
23mod engine_api;
24
25mod adjacency;
26mod apply_redo;
27#[cfg(feature = "research")]
31pub(crate) mod census;
32mod chain;
33mod conflict;
34pub(crate) mod constraint_keys;
35mod count_state;
36mod declared;
37mod degree_stats;
38mod degree_stats_estimate;
39mod degree_stats_incident;
40mod derived_migration;
41mod entity_mutation;
42mod id_vec;
43mod index;
44mod index_lookup;
45mod index_postings;
46mod label_mutation;
47mod label_probe;
48mod prop_read;
49mod query_stats;
50mod redo_preflight;
51mod rel_postings;
52mod restore;
53mod services;
54#[cfg(feature = "research")]
58pub mod sol;
59#[cfg(feature = "research")]
63mod research;
64#[cfg(test)]
65pub(crate) mod test_support;
66mod theater;
67
68pub(crate) use declared::{spatial_holds, trigram_count, RangeSeek, SpatialSeek};
69use declared::{GramIndex, PointIndex, RangeIndex};
70#[cfg(test)]
71pub(crate) use index::CONTAINS_SAMPLE_BOUND;
72use index::{ContainsMemo, Indexes};
73#[cfg(test)]
77pub(crate) use label_probe::take_label_probe_checks;
78pub(crate) use label_probe::LabelProbe;
79pub use query_stats::QueryStats;
80#[cfg(feature = "test-hooks")]
83#[doc(hidden)]
84pub use index::take_index_rebuilds;
85pub use relate_planner::ContainsCount;
86pub(crate) use services::StoreServices;
87
88use theater::TheaterData;
89
90pub(crate) type CoreMap<K, V> = dashmap::DashMap<K, V, crate::hash_seed::FxBuildHasher>;
95
96fn visible_version<Live>(vers: &Chain<Live>, ts: u64) -> Option<VerRef<'_, Live>> {
100 vers.visible_at(ts)
101}
102
103fn live_version<Live>(vers: &Chain<Live>) -> Option<VerRef<'_, Live>> {
111 vers.live()
112}
113
114pub(in crate::graph) struct RelRow {
123 pub(in crate::graph) id: RelId,
124 pub(in crate::graph) start: NodeId,
125 pub(in crate::graph) type_id: u32,
126 pub(in crate::graph) end: NodeId,
127 pub(in crate::graph) ts: Option<i64>,
128}
129
130#[derive(Default)]
136pub(in crate::graph) struct LabelCache(HashMap<NodeId, Vec<u32>>);
137
138impl LabelCache {
139 pub(in crate::graph) fn ensure(&mut self, graph: &Graph, node: NodeId) {
141 self.0
142 .entry(node)
143 .or_insert_with(|| graph.live_label_ids(node));
144 }
145
146 pub(in crate::graph) fn get(&self, node: NodeId) -> &[u32] {
149 self.0
150 .get(&node)
151 .expect("the fold cached every endpoint's labels")
152 .as_slice()
153 }
154}
155
156impl relate_names::TokenResolver for Graph {
160 fn resolve(&self, name: &str) -> relate_names::Token {
161 self.interner.resolve(name)
162 }
163}
164
165impl Graph {
166 pub(in crate::graph) fn live_label_ids(&self, node: NodeId) -> Vec<u32> {
174 self.nodes
175 .get(&node)
176 .and_then(|vers| vers.live().map(|v| v.live.labels.clone()))
177 .unwrap_or_default()
178 }
179}
180
181pub(crate) use theater::{apply_show_overlay, DatabasesCatalog, ShowSchema};
182pub use theater::{CheckpointTheater, DatabaseEntry, SchemaSnapshot};
183
184macro_rules! atomic_fetch_update {
189 ($atom:expr, $set:expr, $fetch:expr, $f:expr) => {{
190 #[allow(
191 deprecated,
192 reason = "fetch_update renamed to try_update in 1.99; try_update needs 1.95, MSRV is 1.88"
193 )]
194 {
195 $atom.fetch_update($set, $fetch, $f)
196 }
197 }};
198}
199
200pub(crate) trait ExhaustibleIdCounter {
205 fn try_alloc_id(&self) -> std::result::Result<i64, i64>;
206}
207
208impl ExhaustibleIdCounter for AtomicI64 {
209 fn try_alloc_id(&self) -> std::result::Result<i64, i64> {
210 atomic_fetch_update!(self, Ordering::Relaxed, Ordering::Relaxed, |id| {
211 if (0..i64::MAX).contains(&id) {
212 Some(id + 1)
213 } else {
214 None
215 }
216 })
217 }
218}
219
220impl ExhaustibleIdCounter for AtomicU64 {
221 fn try_alloc_id(&self) -> std::result::Result<i64, i64> {
222 atomic_fetch_update!(self, Ordering::Relaxed, Ordering::Relaxed, |id| {
223 (id < i64::MAX as u64).then_some(id + 1)
224 })
225 .map(|id| id as i64)
226 .map_err(|id| id as i64)
227 }
228}
229
230pub(crate) fn delete_connected_node_error() -> relate_core::Error {
238 relate_core::Error::execution(format!(
239 "{}: DeleteConnectedNode: Cannot delete node with relationships unless DETACH",
240 relate_error::NestedErrorClass::ConstraintVerificationFailed.as_str(),
241 ))
242}
243
244pub(crate) fn missing_rel_endpoint_error() -> relate_core::Error {
248 relate_core::Error::semantic("cannot create relationship on missing node")
249}
250
251pub(crate) fn alloc_exhaustible_id(counter: &impl ExhaustibleIdCounter, what: &str) -> Result<i64> {
254 counter
255 .try_alloc_id()
256 .map_err(|_| relate_core::Error::execution(format!("{what} ID exhausted")))
257}
258
259#[derive(Debug, Clone, Default)]
260pub struct Procedure {
261 pub name: String,
262 pub arg_names: Vec<String>,
263 pub arg_types: Vec<String>,
265 pub yield_names: Vec<String>,
266 pub rows: Vec<BTreeMap<String, Value>>,
267}
268
269use chain::{Chain, Ver, VerRef};
270use id_vec::IdVec;
271
272type NodeVer = Ver<LiveNode>;
275type RelVer = Ver<LiveRel>;
276
277pub(crate) fn node_version_stride() -> u64 {
278 std::mem::size_of::<NodeVer>() as u64
279}
280
281pub(crate) fn rel_version_stride() -> u64 {
282 std::mem::size_of::<RelVer>() as u64
283}
284
285pub(crate) fn node_slot() -> u64 {
289 std::mem::size_of::<Option<Chain<LiveNode>>>() as u64
290}
291
292pub(crate) fn rel_slot() -> u64 {
293 std::mem::size_of::<Option<Chain<LiveRel>>>() as u64
294}
295
296pub(crate) fn adj_slot() -> u64 {
297 std::mem::size_of::<Option<TypedAdj>>() as u64
298}
299
300fn sealed_slot() -> u64 {
302 std::mem::size_of::<Option<SealedAdj>>() as u64
303}
304
305fn sealed_value() -> u64 {
306 std::mem::size_of::<SealedAdj>() as u64
307}
308
309pub(crate) fn node_value() -> u64 {
310 std::mem::size_of::<Chain<LiveNode>>() as u64
311}
312
313pub(crate) fn rel_value() -> u64 {
314 std::mem::size_of::<Chain<LiveRel>>() as u64
315}
316
317fn adj_value() -> u64 {
318 std::mem::size_of::<TypedAdj>() as u64
319}
320
321fn cow<Live: Clone>(write_ts: &AtomicU64, map: &IdVec<Chain<Live>>, id: i64) -> Option<Live> {
323 let ts = write_ts.load(Ordering::Acquire);
324 map.get_mut(&id)?.cow(ts)
325}
326
327#[derive(Debug)]
328pub struct Graph {
329 namespace: Namespace,
334 services: Arc<StoreServices>,
344 next_node_id: AtomicI64,
345 next_rel_id: AtomicI64,
346 published_ts: AtomicU64,
348 write_ts: AtomicU64,
349 in_write: AtomicBool,
350 record_redo: AtomicBool,
351 nodes: IdVec<Chain<LiveNode>>,
352 rels: IdVec<Chain<LiveRel>>,
353 out_adj: IdVec<TypedAdj>,
354 in_adj: IdVec<TypedAdj>,
355 sealed_out: IdVec<SealedAdj>,
360 sealed_in: IdVec<SealedAdj>,
361 count_stats: Mutex<CountStats>,
372 degree_histograms: Mutex<HashMap<(u32, u32), [u64; Self::DEGREE_BUCKETS]>>,
386 constraint_keys: Mutex<ConstraintKeyIndex>,
396 interner: Interner,
397 catalog: Mutex<Catalog>,
398 pub(crate) theater: Mutex<TheaterData>,
399 legacy_unenforced: Mutex<HashMap<String, ConstraintDef>>,
401 stats: Mutex<QueryStats>,
402 indexes: Indexes,
406 contains_memo: Mutex<ContainsMemo>,
413 pending_redo: Mutex<Vec<RedoOp>>,
414 pull_identity: PullIdentityIndex,
416 dirty_nodes: Mutex<HashSet<NodeId>>,
418 dirty_rels: Mutex<HashSet<RelId>>,
419 pins: Box<[AtomicU64]>,
421 pin_cursor: AtomicU64,
422 used_bytes: AtomicU64,
424}
425
426impl Default for Graph {
427 fn default() -> Self {
428 let interner = Interner::default();
429 let indexes = Indexes::new(&interner);
430 Self {
431 namespace: Namespace::Neo4j,
432 services: Arc::new(StoreServices::default()),
433 next_node_id: AtomicI64::new(0),
434 next_rel_id: AtomicI64::new(0),
435 published_ts: AtomicU64::new(0),
436 write_ts: AtomicU64::new(0),
437 in_write: AtomicBool::new(false),
438 record_redo: AtomicBool::new(true),
439 nodes: IdVec::default(),
440 rels: IdVec::default(),
441 out_adj: IdVec::default(),
442 in_adj: IdVec::default(),
443 sealed_out: IdVec::default(),
444 sealed_in: IdVec::default(),
445 count_stats: Mutex::new(CountStats::default()),
446 degree_histograms: Mutex::new(HashMap::new()),
447 constraint_keys: Mutex::new(ConstraintKeyIndex::default()),
448 interner,
449 catalog: Mutex::new(Catalog::default()),
450 theater: Mutex::new(TheaterData::default()),
451 indexes,
452 contains_memo: Mutex::new(ContainsMemo::default()),
453 legacy_unenforced: Mutex::new(HashMap::new()),
454 stats: Mutex::new(QueryStats::default()),
455 pending_redo: Mutex::new(Vec::new()),
456 pull_identity: PullIdentityIndex::default(),
457 dirty_nodes: Mutex::new(HashSet::new()),
458 dirty_rels: Mutex::new(HashSet::new()),
459 pins: (0..PIN_SLOTS).map(|_| AtomicU64::new(PIN_FREE)).collect(),
460 pin_cursor: AtomicU64::new(0),
461 used_bytes: AtomicU64::new(0),
462 }
463 }
464}
465
466const PIN_SLOTS: usize = 256;
469const PIN_FREE: u64 = 0;
470const PIN_CLAIMING: u64 = u64::MAX;
471const PIN_ACQUIRE_RETRIES: u32 = 1024;
476
477pub struct SnapshotPin<'a> {
479 graph: &'a Graph,
480 ts: u64,
481 slot: usize,
482}
483
484impl SnapshotPin<'_> {
485 pub fn ts(&self) -> u64 {
486 self.ts
487 }
488
489 pub fn detach(self) -> usize {
491 let slot = self.slot;
492 std::mem::forget(self);
493 slot
494 }
495}
496
497impl Drop for SnapshotPin<'_> {
498 fn drop(&mut self) {
499 self.graph.unpin_slot(self.slot);
500 }
501}
502
503fn visible(xmin: u64, xmax: u64, ts: u64) -> bool {
504 xmin != 0 && xmin <= ts && (xmax == 0 || xmax > ts)
505}
506
507fn checked_persisted_id(id: i64, what: &str) -> Result<i64> {
508 relate_core::validate_persisted_id(id, what)?;
509 Ok(id + 1)
510}
511
512fn requires_enforced_label(def: &ConstraintDef) -> bool {
513 def.kind
514 .parse::<relate_model::ConstraintType>()
515 .is_ok_and(|kind| kind.is_enforced_label_kind())
516}
517
518fn matching_enforced_label(def: &ConstraintDef, c: &relate_model::Constraint) -> bool {
519 c.label == def.label
520 && c.properties == def.properties
521 && def.kind.parse::<relate_model::ConstraintType>() == Ok(c.constraint_type)
522 && c.property_type == def.property_type
523 && c.constraint_type
524 .enforced_label_site()
525 .is_some_and(|site| site.is_relationship() == def.relationship)
526 && c.enforced_label
527 .as_deref()
528 .is_some_and(|label| !label.is_empty())
529}
530
531fn has_enforced_label(c: &relate_model::Constraint) -> bool {
535 c.constraint_type.is_enforced_label_kind()
536 && c.enforced_label
537 .as_deref()
538 .is_some_and(|label| !label.is_empty())
539}
540
541impl Graph {
542 pub(crate) fn has_property_defaults(&self) -> bool {
548 let theater = self.theater.lock().expect("theater lock poisoned");
549 spec_has_property_defaults(&theater.current_graph_type)
550 }
551
552 pub fn namespace(&self) -> Namespace {
554 self.namespace
555 }
556
557 #[doc(hidden)]
560 pub fn set_namespace(&mut self, namespace: Namespace) {
561 self.namespace = namespace;
562 }
563
564 pub fn commit_ts(&self) -> u64 {
565 self.published_ts.load(Ordering::Acquire)
566 }
567
568 pub(crate) fn in_write_window(&self) -> bool {
574 self.in_write.load(Ordering::Acquire)
575 }
576
577 pub fn set_commit_ts(&self, ts: u64) {
578 self.published_ts.store(ts, Ordering::Release);
579 }
580
581 pub fn used_bytes(&self) -> u64 {
583 self.used_bytes
584 .load(Ordering::Relaxed)
585 .saturating_add(self.interner.bytes())
586 }
587
588 pub fn accounted_bytes(&self) -> u64 {
591 self.structure_bytes().saturating_add(self.interner.bytes())
592 }
593
594 fn structure_bytes(&self) -> u64 {
595 let charge = self.index_charge();
596 let mut n = 0u64;
597 n = n.saturating_add(self.nodes.array_bytes());
598 self.nodes.for_each(|_id, vers| {
599 n = n.saturating_add(crate::memory::node_chain_bytes(vers.shape()));
600 for v in vers.iter() {
601 n = n.saturating_add(crate::memory::live_node_account_live(
602 v.live,
603 &self.interner,
604 &charge,
605 ));
606 }
607 });
608 n = n.saturating_add(self.rels.array_bytes());
609 self.rels.for_each(|_id, vers| {
610 n = n.saturating_add(crate::memory::rel_chain_bytes(vers.shape()));
611 for v in vers.iter() {
612 n = n.saturating_add(crate::memory::live_rel_account_live(v.live));
613 }
614 });
615 n = n.saturating_add(self.out_adj.array_bytes());
616 n = n.saturating_add(self.in_adj.array_bytes());
617 self.out_adj
618 .for_each(|_id, adj| n = n.saturating_add(adj.floor_bytes()));
619 self.in_adj
620 .for_each(|_id, adj| n = n.saturating_add(adj.floor_bytes()));
621 n = n.saturating_add(self.sealed_out.array_bytes());
626 n = n.saturating_add(self.sealed_in.array_bytes());
627 for sealed in [&self.sealed_out, &self.sealed_in] {
628 sealed.for_each(|_id, region| n = n.saturating_add(region.floor_bytes()));
629 }
630 n = n.saturating_add(self.degree_stats_structure_bytes());
638 n = n.saturating_add(self.count_state_structure_bytes());
639 n = n.saturating_add(self.constraint_keys_structure_bytes());
643 n
644 }
645
646 pub fn recompute_used(&self) {
647 self.used_bytes
648 .store(self.structure_bytes(), Ordering::Relaxed);
649 }
650
651 pub fn estimate_redo_delta(&self, ops: &[RedoOp]) -> i64 {
658 self.estimate_redo_delta_with_constraint_growth(ops, None)
659 .total
660 }
661
662 #[doc(hidden)]
667 pub fn estimate_redo_delta_with_constraint_growth(
668 &self,
669 ops: &[RedoOp],
670 constraint_growth: Option<i64>,
671 ) -> crate::memory::RedoDelta {
672 let before = self.index_charge();
673 let after = self.charge_after_ops(ops);
674 let crate::memory::RedoDelta {
675 total: mut delta,
676 tombstone_spill,
677 } = crate::memory::estimate_redo_delta(
678 &self.interner,
679 ops,
680 |id| self.node(id),
681 |id| self.rel_form(id),
682 |id| self.node_chain_shape(id),
683 |id| self.rel_chain_shape(id),
684 self.nodes.span(),
685 self.rels.span(),
686 &after,
687 );
688 delta += self.estimate_adj_delta(ops);
689 delta += self.estimate_intern_delta(ops);
690 delta += self.estimate_stats_entry_growth(ops);
695 delta += match constraint_growth {
699 Some(growth) => growth,
700 None => self.estimate_constraint_key_entry_growth(ops),
701 };
702 if before.as_ref() != &after {
703 self.nodes.for_each(|id, vers| {
704 for v in vers.iter() {
705 let n = v.live.to_node(id, &self.interner);
706 delta += crate::memory::live_node_account(&n, &after) as i64
707 - crate::memory::live_node_account(&n, &before) as i64;
708 }
709 });
710 }
711 crate::memory::RedoDelta {
712 total: delta,
713 tombstone_spill,
714 }
715 }
716
717 fn estimate_adj_delta(&self, ops: &[RedoOp]) -> i64 {
718 let mut out: HashMap<NodeId, Vec<(u32, usize)>> = HashMap::new();
719 let mut inn: HashMap<NodeId, Vec<(u32, usize)>> = HashMap::new();
720 let mut fresh_ids = FreshIds::new();
721 let mut delta = 0i64;
722 let slot = adj_slot();
723 let overflow = crate::memory::overflow_entry_bytes(adj_value());
724 let mut out_span = self.out_adj.span();
725 let mut in_span = self.in_adj.span();
726 let mut out_side = HashSet::new();
727 let mut in_side = HashSet::new();
728 for op in ops {
729 let RedoOp::CreateRel {
730 start,
731 end,
732 rel_type,
733 ..
734 } = op
735 else {
736 continue;
737 };
738 let type_id = fresh_ids.resolve(self, rel_type);
739 if !self.out_adj.contains_key(start) {
740 delta += span_growth(&mut out_span, *start, slot, overflow, &mut out_side);
741 }
742 if !self.in_adj.contains_key(end) {
743 delta += span_growth(&mut in_span, *end, slot, overflow, &mut in_side);
744 }
745 delta += bump_adj(&mut out, *start, type_id, || {
746 hop_counts(&self.out_adj, &self.sealed_out, *start)
747 });
748 delta += bump_adj(&mut inn, *end, type_id, || {
749 hop_counts(&self.in_adj, &self.sealed_in, *end)
750 });
751 }
752 let mut regions: HashSet<(bool, NodeId, u32)> = HashSet::new();
757 let mut sealed_out_span = self.sealed_out.span();
758 let mut sealed_in_span = self.sealed_in.span();
759 let mut sealed_out_side = HashSet::new();
760 let mut sealed_in_side = HashSet::new();
761 let sealed_slot = sealed_slot();
762 let sealed_overflow = crate::memory::overflow_entry_bytes(sealed_value());
763 for op in ops {
764 let RedoOp::DeleteRel { id } = op else {
765 continue;
766 };
767 let Some((start, end, type_id)) = self.rels.get(id).map(|vers| {
768 let newest = vers.last();
770 (newest.live.start, newest.live.end, newest.live.type_id)
771 }) else {
772 continue;
773 };
774 for (incoming, node, sealed) in [
775 (false, start, &self.sealed_out),
776 (true, end, &self.sealed_in),
777 ] {
778 let region = sealed.get(&node);
779 let sealed = region
780 .as_ref()
781 .is_some_and(|region| region.chunk(type_id).is_some());
782 if !sealed && regions.insert((incoming, node, type_id)) {
783 if region.is_none() {
785 let (span, side) = if incoming {
786 (&mut sealed_in_span, &mut sealed_in_side)
787 } else {
788 (&mut sealed_out_span, &mut sealed_out_side)
789 };
790 delta += span_growth(span, node, sealed_slot, sealed_overflow, side);
791 }
792 delta += crate::adjacency::fresh_sealed_region_bytes() as i64;
793 }
794 }
795 }
796 delta
797 }
798
799 fn estimate_intern_delta(&self, ops: &[RedoOp]) -> i64 {
800 let mut seen = HashSet::new();
801 let mut extra = 0i64;
802 let mut consider = |s: &str| {
803 if !seen.insert(s.to_string()) {
804 return;
805 }
806 if self.interner.get_id(s).is_none() {
807 extra += crate::memory::interned_string_bytes(s.len()) as i64;
808 }
809 };
810 for op in ops {
811 match op {
812 RedoOp::CreateNode {
813 labels, properties, ..
814 } => {
815 for label in labels.iter() {
816 consider(label);
817 }
818 for key in properties.keys() {
819 consider(key);
820 }
821 }
822 RedoOp::CreateRel {
823 rel_type,
824 properties,
825 ..
826 } => {
827 consider(rel_type);
828 for key in properties.keys() {
829 consider(key);
830 }
831 }
832 RedoOp::SetNodeProp { key, .. }
833 | RedoOp::RemoveNodeProp { key, .. }
834 | RedoOp::SetRelProp { key, .. }
835 | RedoOp::RemoveRelProp { key, .. } => consider(key),
836 RedoOp::AddLabels { labels, .. } | RedoOp::RemoveLabels { labels, .. } => {
837 for label in labels {
838 consider(label);
839 }
840 }
841 _ => {}
842 }
843 }
844 extra
845 }
846
847 fn index_charge(&self) -> Arc<crate::memory::IndexCharge> {
848 Arc::clone(&self.indexes.charge_cache.lock().unwrap())
849 }
850
851 fn refresh_index_charge(&self) {
852 let charge = {
853 let theater = self.theater.lock().unwrap();
854 Arc::new(crate::memory::IndexCharge::from_details(
855 theater.index_details.values(),
856 ))
857 };
858 *self.indexes.charge_cache.lock().unwrap() = charge;
859 }
860
861 fn charge_after_ops(&self, ops: &[RedoOp]) -> crate::memory::IndexCharge {
862 let theater = self.theater.lock().unwrap();
863 let mut details = theater.index_details.clone();
864 drop(theater);
865 crate::redo::project_index_details(&mut details, ops);
866 crate::memory::IndexCharge::from_details(details.values())
867 }
868
869 fn charge(&self, delta: i64) {
870 if delta > 0 {
871 self.used_bytes.fetch_add(delta as u64, Ordering::Relaxed);
872 } else if delta < 0 {
873 let sub = (-delta) as u64;
874 atomic_fetch_update!(self.used_bytes, Ordering::Relaxed, Ordering::Relaxed, |u| {
875 Some(u.saturating_sub(sub))
876 })
877 .ok();
878 }
879 }
880
881 fn charge_node_swap(&self, before: Option<&Node>, after: Option<&Node>) {
882 let charge = self.index_charge();
883 let b = before
884 .map(|n| crate::memory::live_node_account(n, &charge))
885 .unwrap_or(0);
886 let a = after
887 .map(|n| crate::memory::live_node_account(n, &charge))
888 .unwrap_or(0);
889 self.charge(a as i64 - b as i64);
890 }
891
892 fn charge_rel_after_edit(&self, id: RelId, before_bytes: u64, before_shape: ChainShape) {
893 let after_shape = self.rel_chain_shape(id);
894 let after_bytes = self.visible_rel_account(id);
895 if after_shape != before_shape {
896 let growth = crate::memory::rel_chain_bytes(after_shape) as i64
897 - crate::memory::rel_chain_bytes(before_shape) as i64;
898 self.charge(after_bytes as i64 + growth);
899 } else {
900 self.charge(after_bytes as i64 - before_bytes as i64);
901 }
902 }
903
904 #[cfg(test)]
905 fn node_chain_len(&self, id: NodeId) -> usize {
906 self.nodes.get(&id).map_or(0, |v| v.len())
907 }
908
909 fn node_chain_shape(&self, id: NodeId) -> ChainShape {
910 self.nodes
911 .get(&id)
912 .map_or(ChainShape::Absent, |v| v.shape())
913 }
914
915 fn rel_chain_shape(&self, id: RelId) -> ChainShape {
916 self.rels.get(&id).map_or(ChainShape::Absent, |v| v.shape())
917 }
918
919 fn charge_node_after_edit(&self, id: NodeId, before: Option<&Node>, before_shape: ChainShape) {
921 let after = self.node(id);
922 let after_shape = self.node_chain_shape(id);
923 if after_shape != before_shape {
924 let charge = self.index_charge();
925 let added = after
926 .as_ref()
927 .map(|n| crate::memory::live_node_account(n, &charge))
928 .unwrap_or(0);
929 let growth = crate::memory::node_chain_bytes(after_shape) as i64
930 - crate::memory::node_chain_bytes(before_shape) as i64;
931 self.charge(added as i64 + growth);
932 } else {
933 self.charge_node_swap(before, after.as_ref());
934 }
935 }
936
937 pub fn next_node_id(&self) -> NodeId {
938 self.next_node_id.load(Ordering::Relaxed)
939 }
940
941 pub fn set_next_node_id(&self, id: NodeId) {
942 self.next_node_id.store(id, Ordering::Relaxed);
943 }
944
945 pub fn next_rel_id(&self) -> RelId {
946 self.next_rel_id.load(Ordering::Relaxed)
947 }
948
949 fn mark_node_dirty(&self, id: NodeId) {
950 self.dirty_nodes.lock().unwrap().insert(id);
951 }
952
953 fn mark_rel_dirty(&self, id: RelId) {
954 self.dirty_rels.lock().unwrap().insert(id);
955 }
956
957 pub fn pin_now(&self) -> Result<SnapshotPin<'_>> {
965 self.pin_now_with_retry(std::thread::yield_now)
966 }
967
968 fn pin_now_with_retry(&self, mut retry: impl FnMut()) -> Result<SnapshotPin<'_>> {
970 let start = self.pin_cursor.fetch_add(1, Ordering::Relaxed) as usize;
971 for _ in 0..PIN_ACQUIRE_RETRIES {
972 for i in 0..PIN_SLOTS {
973 let slot = (start + i) % PIN_SLOTS;
974 if self.pins[slot]
975 .compare_exchange(PIN_FREE, PIN_CLAIMING, Ordering::AcqRel, Ordering::Acquire)
976 .is_ok()
977 {
978 let ts = self.commit_ts();
979 self.pins[slot].store(ts.saturating_add(1), Ordering::Release);
980 return Ok(SnapshotPin {
981 graph: self,
982 ts,
983 slot,
984 });
985 }
986 }
987 retry();
988 }
989 Err(relate_core::Error::execution(format!(
990 "snapshot pin: all {PIN_SLOTS} slots are held"
991 )))
992 }
993
994 pub fn unpin_slot(&self, slot: usize) {
995 self.pins[slot].store(PIN_FREE, Ordering::Release);
996 }
997
998 pub fn snapshot_pinned(&self) -> bool {
1000 self.pins
1001 .iter()
1002 .any(|slot| slot.load(Ordering::Acquire) != PIN_FREE)
1003 }
1004
1005 pub fn gc_horizon(&self) -> u64 {
1007 let commit = self.commit_ts();
1008 let mut min_pin: Option<u64> = None;
1009 for slot in self.pins.iter() {
1010 let v = slot.load(Ordering::Acquire);
1011 if v == PIN_CLAIMING {
1012 return 0;
1013 }
1014 if v != PIN_FREE {
1015 let ts = v - 1;
1016 min_pin = Some(min_pin.map_or(ts, |m| m.min(ts)));
1017 }
1018 }
1019 min_pin.unwrap_or(commit).min(commit)
1020 }
1021
1022 pub fn set_next_rel_id(&self, id: RelId) {
1023 self.next_rel_id.store(id, Ordering::Relaxed);
1024 }
1025
1026 fn read_ts(&self) -> u64 {
1027 if self.in_write.load(Ordering::Acquire) {
1028 self.write_ts.load(Ordering::Acquire)
1029 } else {
1030 self.commit_ts()
1031 }
1032 }
1033
1034 pub fn begin_write(&self) -> Result<()> {
1037 let ts = self
1038 .commit_ts()
1039 .checked_add(1)
1040 .filter(|ts| *ts < u64::MAX)
1041 .ok_or_else(|| relate_core::Error::execution("write timestamp exhausted"))?;
1042 self.begin_write_at(ts)
1043 }
1044
1045 pub fn begin_write_at(&self, write_ts: u64) -> Result<()> {
1048 if write_ts == u64::MAX {
1049 return Err(relate_core::Error::execution("write timestamp exhausted"));
1050 }
1051 self.in_write.store(true, Ordering::Release);
1052 self.write_ts.store(write_ts, Ordering::Release);
1053 self.pending_redo.lock().unwrap().clear();
1054 self.record_redo.store(true, Ordering::Release);
1055 self.reset_stats();
1056 Ok(())
1057 }
1058
1059 fn alloc_node_id(&self) -> Result<NodeId> {
1060 alloc_exhaustible_id(&self.next_node_id, "node")
1061 }
1062
1063 fn alloc_rel_id(&self) -> Result<RelId> {
1064 alloc_exhaustible_id(&self.next_rel_id, "relationship")
1065 }
1066
1067 pub fn pending_commit_ts(&self) -> u64 {
1068 self.write_ts.load(Ordering::Acquire)
1069 }
1070
1071 pub fn take_redo(&self) -> Vec<RedoOp> {
1072 std::mem::take(&mut *self.pending_redo.lock().unwrap())
1073 }
1074
1075 pub fn commit_write(&self) {
1077 self.set_commit_ts(self.write_ts.load(Ordering::Acquire));
1078 self.in_write.store(false, Ordering::Release);
1079 self.pending_redo.lock().unwrap().clear();
1080 }
1081
1082 pub fn abort_write(&self) {
1083 let ts = self.write_ts.load(Ordering::Acquire);
1084 self.nodes.retain(|_, vers| vers.abort(ts));
1085 self.rels.retain(|_, vers| vers.abort(ts));
1086 self.in_write.store(false, Ordering::Release);
1087 self.pending_redo.lock().unwrap().clear();
1088 self.rebuild_adj();
1089 self.rebuild_indexes();
1090 }
1091
1092 pub fn reset_stats(&self) {
1093 *self.stats.lock().unwrap() = QueryStats::default();
1094 }
1095
1096 pub fn node_at(&self, id: NodeId, ts: u64) -> Option<Node> {
1097 self.nodes
1098 .get(&id)
1099 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_node(id, &self.interner)))
1100 }
1101
1102 pub fn node_labels_at(&self, id: NodeId, ts: u64) -> Option<Vec<String>> {
1106 self.nodes.get(&id).and_then(|vers| {
1107 visible_version(&vers, ts).map(|v| v.live.label_strings(&self.interner))
1108 })
1109 }
1110
1111 pub fn rel_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
1112 self.rels
1113 .get(&id)
1114 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_rel(id, &self.interner)))
1115 }
1116
1117 pub fn rel_ends_at(&self, id: RelId, ts: u64) -> Option<(NodeId, NodeId)> {
1119 self.rels
1120 .get(&id)
1121 .and_then(|vers| visible_version(&vers, ts).map(|v| (v.live.start, v.live.end)))
1122 }
1123
1124 fn rel_live_identity(&self, id: RelId) -> Option<(NodeId, NodeId, u32)> {
1134 self.rels.get(&id).and_then(|vers| {
1135 live_version(&vers).map(|v| (v.live.start, v.live.end, v.live.type_id))
1136 })
1137 }
1138
1139 pub fn node_stub_at(&self, id: NodeId, ts: u64) -> Option<Node> {
1140 self.nodes
1141 .get(&id)
1142 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id, &self.interner)))
1143 }
1144
1145 pub fn rel_stub_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
1146 self.rels
1147 .get(&id)
1148 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id)))
1149 }
1150
1151 pub fn node_prop_at(&self, id: NodeId, ts: u64, key: &str) -> Option<Value> {
1152 self.nodes.get(&id).and_then(|vers| {
1153 visible_version(&vers, ts).and_then(|v| v.live.prop(&self.interner, key))
1154 })
1155 }
1156
1157 pub fn rel_prop_at(&self, id: RelId, ts: u64, key: &str) -> Option<Value> {
1158 self.rels.get(&id).and_then(|vers| {
1159 visible_version(&vers, ts).and_then(|v| v.live.payload.get(&self.interner, key))
1160 })
1161 }
1162
1163 pub fn node_prop_keys_at(&self, id: NodeId, ts: u64) -> Vec<String> {
1164 self.nodes
1165 .get(&id)
1166 .and_then(|vers| {
1167 vers.visible_at(ts)
1168 .map(|v| v.live.props.keys_as_strings(&self.interner))
1169 })
1170 .unwrap_or_default()
1171 }
1172
1173 pub fn rel_prop_keys_at(&self, id: RelId, ts: u64) -> Vec<String> {
1174 self.rels
1175 .get(&id)
1176 .and_then(|vers| {
1177 vers.visible_at(ts)
1178 .map(|v| v.live.payload.keys(&self.interner))
1179 })
1180 .unwrap_or_default()
1181 }
1182
1183 pub(crate) fn rel_visible_at(&self, id: RelId, ts: u64) -> bool {
1184 self.rels
1185 .get(&id)
1186 .is_some_and(|vers| visible_version(&vers, ts).is_some())
1187 }
1188
1189 pub fn node(&self, id: NodeId) -> Option<Node> {
1190 self.node_at(id, self.read_ts())
1191 }
1192
1193 pub fn rel(&self, id: RelId) -> Option<Relationship> {
1194 self.rel_at(id, self.read_ts())
1195 }
1196
1197 fn visible_rel_account(&self, id: RelId) -> u64 {
1200 let ts = self.read_ts();
1201 self.rels
1202 .get(&id)
1203 .and_then(|vers| {
1204 vers.visible_at(ts)
1205 .map(|v| crate::memory::live_rel_account_live(v.live))
1206 })
1207 .unwrap_or(0)
1208 }
1209
1210 fn rel_form(&self, id: RelId) -> Option<crate::store::PayloadForm> {
1211 let ts = self.read_ts();
1212 self.rels.get(&id).and_then(|vers| {
1213 vers.visible_at(ts)
1214 .map(|v| v.live.payload.form(&self.interner))
1215 })
1216 }
1217
1218 pub fn node_exists(&self, id: NodeId) -> bool {
1219 self.node_visible_at(id, self.read_ts())
1220 }
1221
1222 pub fn rel_exists(&self, id: RelId) -> bool {
1223 self.rel_visible_at(id, self.read_ts())
1224 }
1225
1226 pub fn live_node_count(&self) -> usize {
1227 self.all_node_ids().len()
1228 }
1229
1230 fn recording(&self) -> bool {
1232 self.in_write.load(Ordering::Acquire) && self.record_redo.load(Ordering::Acquire)
1233 }
1234
1235 fn push_redo(&self, op: RedoOp) {
1236 if self.recording() {
1237 self.pending_redo.lock().unwrap().push(op);
1238 }
1239 }
1240
1241 fn bump_stats(&self, f: impl FnOnce(&mut QueryStats)) {
1242 f(&mut self.stats.lock().unwrap());
1243 }
1244
1245 fn xmin_for_install(&self) -> u64 {
1246 if self.in_write.load(Ordering::Acquire) {
1247 self.write_ts.load(Ordering::Acquire)
1248 } else {
1249 let ts = self.commit_ts();
1250 if ts == 0 {
1251 self.set_commit_ts(1);
1252 1
1253 } else {
1254 ts
1255 }
1256 }
1257 }
1258
1259 pub fn named_indexes(&self) -> Vec<IndexDef> {
1260 self.catalog
1261 .lock()
1262 .unwrap()
1263 .indexes
1264 .values()
1265 .cloned()
1266 .collect()
1267 }
1268
1269 pub fn schema_snapshot(&self) -> SchemaSnapshot {
1274 self.schema_snapshot_with_hook(|| {})
1275 }
1276
1277 fn schema_snapshot_with_hook(&self, after_catalog: impl FnOnce()) -> SchemaSnapshot {
1278 let (indexes, constraints) = {
1279 let catalog = self.catalog.lock().unwrap();
1280 (
1281 catalog.indexes.values().cloned().collect(),
1282 catalog.constraints.values().cloned().collect(),
1283 )
1284 };
1285 after_catalog();
1286 let show = self.capture_show_schema();
1291 SchemaSnapshot {
1292 indexes,
1293 constraints,
1294 show,
1295 }
1296 }
1297
1298 pub(crate) fn capture_show_schema(&self) -> ShowSchema {
1301 ShowSchema::capture(self.databases().snapshot(), &self.theater.lock().unwrap())
1302 }
1303
1304 pub fn named_constraints(&self) -> Vec<ConstraintDef> {
1305 self.catalog
1306 .lock()
1307 .unwrap()
1308 .constraints
1309 .values()
1310 .cloned()
1311 .collect()
1312 }
1313
1314 pub fn install_named_constraint(&self, def: ConstraintDef) -> Result<()> {
1321 self.catalog.lock().unwrap().insert_constraint(def)
1322 }
1323
1324 pub fn named_index(&self, name: &str) -> Option<IndexDef> {
1325 self.catalog.lock().unwrap().indexes.get(name).cloned()
1326 }
1327
1328 pub fn has_constraint(&self, name: &str) -> bool {
1330 self.catalog.lock().unwrap().constraints.contains_key(name)
1331 }
1332
1333 pub fn named_index_by_schema(&self, label: &str, property: &str) -> Option<IndexDef> {
1334 self.catalog
1335 .lock()
1336 .unwrap()
1337 .index_by_schema(label, property)
1338 .cloned()
1339 }
1340
1341 pub fn install_named_index(&self, def: IndexDef) -> relate_core::Result<()> {
1342 self.catalog.lock().unwrap().insert_index(def)
1343 }
1344
1345 pub fn node_value(&self, id: NodeId) -> Value {
1346 self.node(id).map(Value::from_node).unwrap_or(Value::Null)
1347 }
1348
1349 pub fn rel_value(&self, id: RelId) -> Value {
1350 self.rel(id)
1351 .map(Value::from_relationship)
1352 .unwrap_or(Value::Null)
1353 }
1354
1355 pub fn pull_identity_get(&self, source: &str, kind: PullKind, remote_id: &str) -> Option<i64> {
1356 self.pull_identity.get(source, kind, remote_id)
1357 }
1358
1359 pub fn pull_identity_put(
1360 &self,
1361 source: String,
1362 kind: PullKind,
1363 remote_id: String,
1364 local_id: i64,
1365 ) {
1366 self.pull_identity.put(source, kind, remote_id, local_id);
1367 }
1368
1369 pub fn drop_pull_identity(&self, kind: PullKind, local_id: i64) {
1370 self.pull_identity.remove(kind, local_id);
1371 }
1372}
1373pub(crate) fn spec_has_property_defaults(spec: &crate::graph_type::GraphTypeSpec) -> bool {
1382 let identifying: std::collections::BTreeSet<&str> = spec
1383 .node_types
1384 .iter()
1385 .map(|n| n.identifying_label.as_str())
1386 .collect();
1387 spec.node_types.iter().any(|n| {
1388 n.properties.iter().any(|p| p.default_value.is_some())
1389 || n.implied_labels
1390 .iter()
1391 .any(|l| identifying.contains(l.as_str()))
1392 }) || spec
1393 .edge_types
1394 .iter()
1395 .any(|e| e.properties.iter().any(|p| p.default_value.is_some()))
1396}
1397
1398fn hop_counts(map: &IdVec<TypedAdj>, sealed: &IdVec<SealedAdj>, node: NodeId) -> Vec<(u32, usize)> {
1399 map.get(&node)
1400 .map(|adj| {
1401 adj.chunk_lens(sealed.get(&node).as_deref())
1402 .map(|(type_id, delta, sealed)| (type_id, delta + sealed))
1403 .collect()
1404 })
1405 .unwrap_or_default()
1406}
1407
1408struct FreshIds {
1418 fresh: HashMap<String, u32>,
1419 next: u32,
1420}
1421
1422impl FreshIds {
1423 fn new() -> Self {
1424 Self {
1425 fresh: HashMap::new(),
1426 next: u32::MAX,
1427 }
1428 }
1429
1430 fn resolve(&mut self, g: &Graph, name: &str) -> u32 {
1433 g.interner
1434 .get_id(name)
1435 .or_else(|| self.fresh.get(name).copied())
1436 .unwrap_or_else(|| {
1437 let id = self.next;
1438 self.next = self.next.saturating_sub(1);
1439 self.fresh.insert(name.to_string(), id);
1440 id
1441 })
1442 }
1443}
1444
1445fn span_growth(
1449 span: &mut usize,
1450 id: NodeId,
1451 slot: u64,
1452 overflow: u64,
1453 side: &mut HashSet<NodeId>,
1454) -> i64 {
1455 let Some(idx) = usize::try_from(id).ok() else {
1456 return 0;
1457 };
1458 let need = idx.saturating_add(1);
1459 if need <= *span {
1460 return 0;
1461 }
1462 let Some(after) = crate::memory::reservable_span_bytes(need, slot) else {
1463 return if side.insert(id) { overflow as i64 } else { 0 };
1464 };
1465 let before = crate::memory::id_vec_bytes(*span, slot);
1466 *span = need;
1467 after as i64 - before as i64
1468}
1469
1470fn adj_floor(map: &IdVec<TypedAdj>, sealed: &IdVec<SealedAdj>, node: NodeId) -> u64 {
1473 map.get(&node).map(|adj| adj.floor_bytes()).unwrap_or(0)
1474 + sealed.get(&node).map_or(0, |region| region.floor_bytes())
1475}
1476
1477fn bump_adj(
1478 sim: &mut HashMap<NodeId, Vec<(u32, usize)>>,
1479 node: NodeId,
1480 type_id: u32,
1481 init: impl FnOnce() -> Vec<(u32, usize)>,
1482) -> i64 {
1483 let chunks = sim.entry(node).or_insert_with(init);
1484 let before =
1485 crate::memory::adjacency_bytes(&chunks.iter().map(|(_, n)| *n).collect::<Vec<_>>());
1486 if let Some(slot) = chunks.iter_mut().find(|c| c.0 == type_id) {
1487 slot.1 += 1;
1488 } else {
1489 chunks.push((type_id, 1));
1490 }
1491 let after = crate::memory::adjacency_bytes(&chunks.iter().map(|(_, n)| *n).collect::<Vec<_>>());
1492 after as i64 - before as i64
1493}
1494impl Graph {
1495 pub fn all_rel_ids(&self) -> Vec<RelId> {
1496 self.all_rel_ids_at(self.read_ts())
1497 }
1498
1499 pub fn all_rel_ids_at(&self, ts: u64) -> Vec<RelId> {
1500 let mut ids: Vec<_> = self
1501 .rels
1502 .keys()
1503 .into_iter()
1504 .filter(|id| self.rel_visible_at(*id, ts))
1505 .collect();
1506 ids.sort();
1507 ids
1508 }
1509
1510 pub fn all_node_ids(&self) -> Vec<NodeId> {
1511 self.all_node_ids_at(self.read_ts())
1512 }
1513
1514 pub fn all_node_ids_at(&self, ts: u64) -> Vec<NodeId> {
1515 let mut ids: Vec<_> = self
1516 .nodes
1517 .keys()
1518 .into_iter()
1519 .filter(|id| self.node_visible_at(*id, ts))
1520 .collect();
1521 ids.sort();
1522 ids
1523 }
1524
1525 pub(crate) fn node_visible_at(&self, id: NodeId, ts: u64) -> bool {
1526 self.nodes
1527 .get(&id)
1528 .is_some_and(|vers| visible_version(&vers, ts).is_some())
1529 }
1530}
1531
1532#[cfg(test)]
1533mod tests;