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
19pub(crate) use count_state::{CountProbe, LabelSetCount};
22
23#[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#[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#[cfg(feature = "research")]
96pub mod sol;
97#[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#[cfg(test)]
119pub(crate) use label_probe::take_label_probe_checks;
120pub(crate) use label_probe::LabelProbe;
121pub use query_stats::QueryStats;
122#[cfg(feature = "test-hooks")]
125#[doc(hidden)]
126pub use index::take_index_rebuilds;
127#[cfg(feature = "test-hooks")]
130#[doc(hidden)]
131pub use vector_matrix::take_vector_matrix_serves;
132#[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
145pub(crate) type CoreMap<K, V> = dashmap::DashMap<K, V, crate::hash_seed::FxBuildHasher>;
150
151impl 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 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
179pub(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 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
214pub(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
228pub(crate) fn missing_rel_endpoint_error() -> relate_core::Error {
232 relate_core::Error::semantic("cannot create relationship on missing node")
233}
234
235pub(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 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
257type 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
270pub(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
285fn 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
303fn 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 namespace: Namespace,
316 services: Arc<StoreServices>,
326 attached_store: prop_store::AttachedStore,
331 next_node_id: AtomicI64,
332 next_rel_id: AtomicI64,
333 published_ts: AtomicU64,
335 write_ts: AtomicU64,
336 in_write: AtomicBool,
337 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 sealed_out: SealedArena,
356 sealed_in: SealedArena,
357 count_stats: Mutex<CountStats>,
368 degree_histograms: Mutex<degree_stats::DegreeHistograms>,
382 constraint_keys: Mutex<ConstraintKeyIndex>,
392 interner: Interner,
393 catalog: Mutex<Catalog>,
394 pub(crate) theater: Mutex<TheaterData>,
395 legacy_unenforced: Mutex<HashMap<String, ConstraintDef>>,
397 stats: Mutex<QueryStats>,
398 indexes: Indexes,
402 contains_memo: Mutex<ContainsMemo>,
409 pending_redo: Mutex<Vec<RedoOp>>,
410 pull_identity: PullIdentityIndex,
412 changed_tokens: Mutex<AppliedTokenChanges>,
418 dirty_nodes: Mutex<HashSet<NodeId>>,
420 dirty_rels: Mutex<HashSet<RelId>>,
421
422 pins: Box<[AtomicU64]>,
424 pin_cursor: AtomicU64,
425 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
501pub(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
517fn 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 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 pub fn namespace(&self) -> Namespace {
540 self.namespace
541 }
542
543 #[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 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 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 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 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 fn end_write(&self, commit_ts: u64) {
650 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 fn close_window(&self) {
671 self.in_write.store(false, Ordering::Release);
672 self.pending_redo.lock().unwrap().clear();
673 }
674
675 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 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 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 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 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 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 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
855pub(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 pub(crate) fn selects(wanted: Option<u32>, label: u32) -> bool {
884 wanted.is_none_or(|wanted| wanted == label)
885 }
886
887 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;