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 label_mutation;
64mod label_probe;
65mod pair_postings;
66mod pin;
67mod prop_read;
68mod query_stats;
69pub use pin::SnapshotPin;
70#[cfg(test)]
71use pin::PIN_ACQUIRE_RETRIES;
72#[cfg(test)]
73use pin::PIN_CLAIMING;
74use pin::{PIN_FREE, PIN_SLOTS};
75mod rebuild;
76mod redo_preflight;
77mod rel_postings;
78mod restore;
79mod schema_api;
80mod services;
81mod shard;
82#[cfg(feature = "research")]
86pub mod sol;
87#[cfg(feature = "research")]
91mod research;
92#[cfg(test)]
93pub(crate) mod test_support;
94mod theater;
95mod unposted;
96
97pub(crate) use declared::{spatial_holds, trigram_count, Extremum, RangeSeek, SpatialSeek};
98use declared::{GramIndex, PointIndex, RangeIndex};
99#[cfg(test)]
100pub(crate) use index::CONTAINS_SAMPLE_BOUND;
101use index::{ContainsMemo, Indexes};
102#[cfg(test)]
106pub(crate) use label_probe::take_label_probe_checks;
107pub(crate) use label_probe::LabelProbe;
108pub use query_stats::QueryStats;
109#[cfg(feature = "test-hooks")]
112#[doc(hidden)]
113pub use index::take_index_rebuilds;
114#[cfg(feature = "test-hooks")]
117#[doc(hidden)]
118pub use adjacency::Side;
119#[cfg(test)]
120pub(crate) use adjacency::HOP_BATCH;
121pub(crate) use adjacency::{HopBuf, PeerHop};
122pub use relate_planner::ContainsCount;
123pub(crate) use services::StoreServices;
124
125use theater::TheaterData;
126
127pub(crate) type CoreMap<K, V> = dashmap::DashMap<K, V, crate::hash_seed::FxBuildHasher>;
132
133impl relate_names::TokenResolver for Graph {
137 fn resolve(&self, name: &str) -> relate_names::Token {
138 self.interner.resolve(name)
139 }
140}
141
142impl Graph {
143 pub(in crate::graph) fn live_label_ids(&self, node: NodeId) -> Vec<u32> {
151 self.nodes
152 .get(&node)
153 .and_then(|vers| vers.live().map(|v| v.live.labels.clone()))
154 .unwrap_or_default()
155 }
156}
157
158pub(crate) use theater::{apply_show_overlay, DatabasesCatalog, ShowSchema};
159pub use theater::{CheckpointTheater, DatabaseEntry, SchemaSnapshot};
160
161pub(crate) trait ExhaustibleIdCounter {
166 fn try_alloc_id(&self) -> Option<i64>;
167}
168
169impl ExhaustibleIdCounter for AtomicI64 {
170 fn try_alloc_id(&self) -> Option<i64> {
171 self.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| {
176 if (0..i64::MAX).contains(&id) {
177 Some(id + 1)
178 } else {
179 None
180 }
181 })
182 .ok()
183 }
184}
185
186impl ExhaustibleIdCounter for AtomicU64 {
187 fn try_alloc_id(&self) -> Option<i64> {
188 self.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| {
189 (id < i64::MAX as u64).then_some(id + 1)
190 })
191 .ok()
192 .map(|id| id as i64)
193 }
194}
195
196pub(crate) fn delete_connected_node_error() -> relate_core::Error {
204 relate_core::Error::execution(format!(
205 "{}: DeleteConnectedNode: Cannot delete node with relationships unless DETACH",
206 relate_error::NestedErrorClass::ConstraintVerificationFailed.as_str(),
207 ))
208}
209
210pub(crate) fn missing_rel_endpoint_error() -> relate_core::Error {
214 relate_core::Error::semantic("cannot create relationship on missing node")
215}
216
217pub(crate) fn alloc_exhaustible_id(counter: &impl ExhaustibleIdCounter, what: &str) -> Result<i64> {
220 counter
221 .try_alloc_id()
222 .ok_or_else(|| relate_core::Error::execution(format!("{what} ID exhausted")))
223}
224
225#[derive(Debug, Clone, Default)]
226pub struct Procedure {
227 pub name: String,
228 pub arg_names: Vec<String>,
229 pub arg_types: Vec<String>,
231 pub yield_names: Vec<String>,
232 pub rows: Vec<BTreeMap<String, Value>>,
233}
234
235use access::{live_version, visible_version};
236use chain::{Chain, Ver};
237use id_vec::IdVec;
238
239type NodeVer = Ver<LiveNode>;
242type RelVer = Ver<LiveRel>;
243
244pub(crate) fn node_version_stride() -> u64 {
245 std::mem::size_of::<NodeVer>() as u64
246}
247
248pub(crate) fn rel_version_stride() -> u64 {
249 std::mem::size_of::<RelVer>() as u64
250}
251
252pub(crate) fn node_slot() -> u64 {
256 id_vec::slot::<Chain<LiveNode>>()
257}
258
259pub(crate) fn rel_slot() -> u64 {
260 id_vec::slot::<Chain<LiveRel>>()
261}
262
263pub(crate) fn adj_slot() -> u64 {
264 id_vec::slot::<TypedAdj>()
265}
266
267fn sealed_slot() -> u64 {
270 crate::adjacency::span_stride()
271}
272
273pub(crate) fn node_value() -> u64 {
274 std::mem::size_of::<Chain<LiveNode>>() as u64
275}
276
277pub(crate) fn rel_value() -> u64 {
278 std::mem::size_of::<Chain<LiveRel>>() as u64
279}
280
281fn adj_value() -> u64 {
282 std::mem::size_of::<TypedAdj>() as u64
283}
284
285fn cow<Live: Clone>(write_ts: &AtomicU64, map: &IdVec<Chain<Live>>, id: i64) -> Option<Live> {
287 let ts = write_ts.load(Ordering::Acquire);
288 map.get_mut(&id)?.cow(ts)
289}
290
291#[derive(Debug)]
292pub struct Graph {
293 namespace: Namespace,
298 services: Arc<StoreServices>,
308 next_node_id: AtomicI64,
309 next_rel_id: AtomicI64,
310 published_ts: AtomicU64,
312 write_ts: AtomicU64,
313 in_write: AtomicBool,
314 restoring: AtomicBool,
322 record_redo: AtomicBool,
323 nodes: IdVec<Chain<LiveNode>>,
324 rels: IdVec<Chain<LiveRel>>,
325 out_adj: IdVec<TypedAdj>,
326 in_adj: IdVec<TypedAdj>,
327 sealed_out: SealedArena,
333 sealed_in: SealedArena,
334 count_stats: Mutex<CountStats>,
345 degree_histograms: Mutex<degree_stats::DegreeHistograms>,
359 constraint_keys: Mutex<ConstraintKeyIndex>,
369 interner: Interner,
370 catalog: Mutex<Catalog>,
371 pub(crate) theater: Mutex<TheaterData>,
372 legacy_unenforced: Mutex<HashMap<String, ConstraintDef>>,
374 stats: Mutex<QueryStats>,
375 indexes: Indexes,
379 contains_memo: Mutex<ContainsMemo>,
386 pending_redo: Mutex<Vec<RedoOp>>,
387 pull_identity: PullIdentityIndex,
389 dirty_nodes: Mutex<HashSet<NodeId>>,
391 dirty_rels: Mutex<HashSet<RelId>>,
392 pins: Box<[AtomicU64]>,
394 pin_cursor: AtomicU64,
395 used_bytes: AtomicU64,
397}
398
399impl Default for Graph {
400 fn default() -> Self {
401 let interner = Interner::default();
402 let indexes = Indexes::new(&interner);
403 Self {
404 namespace: Namespace::Neo4j,
405 services: Arc::new(StoreServices::default()),
406 next_node_id: AtomicI64::new(0),
407 next_rel_id: AtomicI64::new(0),
408 published_ts: AtomicU64::new(0),
409 write_ts: AtomicU64::new(0),
410 in_write: AtomicBool::new(false),
411 restoring: AtomicBool::new(true),
412 record_redo: AtomicBool::new(true),
413 nodes: IdVec::default(),
414 rels: IdVec::default(),
415 out_adj: IdVec::default(),
416 in_adj: IdVec::default(),
417 sealed_out: SealedArena::default(),
418 sealed_in: SealedArena::default(),
419 count_stats: Mutex::new(CountStats::default()),
420 degree_histograms: Mutex::new(degree_stats::DegreeHistograms::default()),
421 constraint_keys: Mutex::new(ConstraintKeyIndex::default()),
422 interner,
423 catalog: Mutex::new(Catalog::default()),
424 theater: Mutex::new(TheaterData::default()),
425 indexes,
426 contains_memo: Mutex::new(ContainsMemo::default()),
427 legacy_unenforced: Mutex::new(HashMap::new()),
428 stats: Mutex::new(QueryStats::default()),
429 pending_redo: Mutex::new(Vec::new()),
430 pull_identity: PullIdentityIndex::default(),
431 dirty_nodes: Mutex::new(HashSet::new()),
432 dirty_rels: Mutex::new(HashSet::new()),
433 pins: (0..PIN_SLOTS).map(|_| AtomicU64::new(PIN_FREE)).collect(),
434 pin_cursor: AtomicU64::new(0),
435 used_bytes: AtomicU64::new(0),
436 }
437 }
438}
439
440fn visible(xmin: u64, xmax: u64, ts: u64) -> bool {
441 xmin != 0 && xmin <= ts && (xmax == 0 || xmax > ts)
442}
443
444fn checked_persisted_id(id: i64, what: &str) -> Result<i64> {
445 relate_core::validate_persisted_id(id, what)?;
446 Ok(id + 1)
447}
448
449fn requires_enforced_label(def: &ConstraintDef) -> bool {
450 def.kind
451 .parse::<relate_model::ConstraintType>()
452 .is_ok_and(|kind| kind.is_enforced_label_kind())
453}
454
455fn matching_enforced_label(def: &ConstraintDef, c: &relate_model::Constraint) -> bool {
456 c.label == def.label
457 && c.properties == def.properties
458 && def.kind.parse::<relate_model::ConstraintType>() == Ok(c.constraint_type)
459 && c.property_type == def.property_type
460 && c.constraint_type
461 .enforced_label_site()
462 .is_some_and(|site| site.is_relationship() == def.relationship)
463 && c.enforced_label
464 .as_deref()
465 .is_some_and(|label| !label.is_empty())
466}
467
468pub(crate) fn resolve_enforced_label(def: &mut ConstraintDef, twin_label: Option<&str>) {
479 if def.enforced_label.is_none() {
480 def.enforced_label = twin_label.map(str::to_string);
481 }
482}
483
484fn has_enforced_label(c: &relate_model::Constraint) -> bool {
488 c.constraint_type.is_enforced_label_kind()
489 && c.enforced_label
490 .as_deref()
491 .is_some_and(|label| !label.is_empty())
492}
493
494impl Graph {
495 pub(crate) fn has_property_defaults(&self) -> bool {
501 let theater = self.theater.lock().expect("theater lock poisoned");
502 spec_has_property_defaults(&theater.current_graph_type)
503 }
504
505 pub fn namespace(&self) -> Namespace {
507 self.namespace
508 }
509
510 #[doc(hidden)]
513 pub fn set_namespace(&mut self, namespace: Namespace) {
514 self.namespace = namespace;
515 }
516
517 pub fn commit_ts(&self) -> u64 {
518 self.published_ts.load(Ordering::Acquire)
519 }
520
521 pub(crate) fn in_write_window(&self) -> bool {
527 self.in_write.load(Ordering::Acquire)
528 }
529
530 pub fn set_commit_ts(&self, ts: u64) {
531 self.published_ts.store(ts, Ordering::Release);
532 }
533
534 pub fn next_node_id(&self) -> NodeId {
535 self.next_node_id.load(Ordering::Relaxed)
536 }
537
538 pub fn set_next_node_id(&self, id: NodeId) {
539 self.next_node_id.store(id, Ordering::Relaxed);
540 }
541
542 pub fn next_rel_id(&self) -> RelId {
543 self.next_rel_id.load(Ordering::Relaxed)
544 }
545
546 fn mark_node_dirty(&self, id: NodeId) {
547 self.dirty_nodes.lock().unwrap().insert(id);
548 }
549
550 fn mark_rel_dirty(&self, id: RelId) {
551 self.dirty_rels.lock().unwrap().insert(id);
552 }
553
554 pub fn set_next_rel_id(&self, id: RelId) {
555 self.next_rel_id.store(id, Ordering::Relaxed);
556 }
557
558 fn read_ts(&self) -> u64 {
559 if self.in_write.load(Ordering::Acquire) {
560 self.write_ts.load(Ordering::Acquire)
561 } else {
562 self.commit_ts()
563 }
564 }
565
566 pub fn begin_write(&self) -> Result<()> {
569 let ts = self
570 .commit_ts()
571 .checked_add(1)
572 .filter(|ts| *ts < u64::MAX)
573 .ok_or_else(|| relate_core::Error::execution("write timestamp exhausted"))?;
574 self.begin_write_at(ts)
575 }
576
577 pub fn begin_write_at(&self, write_ts: u64) -> Result<()> {
580 if write_ts == u64::MAX {
581 return Err(relate_core::Error::execution("write timestamp exhausted"));
582 }
583 self.in_write.store(true, Ordering::Release);
584 self.write_ts.store(write_ts, Ordering::Release);
585 self.pending_redo.lock().unwrap().clear();
586 self.record_redo.store(true, Ordering::Release);
587 self.reset_stats();
588 Ok(())
589 }
590
591 fn alloc_node_id(&self) -> Result<NodeId> {
592 alloc_exhaustible_id(&self.next_node_id, "node")
593 }
594
595 fn alloc_rel_id(&self) -> Result<RelId> {
596 alloc_exhaustible_id(&self.next_rel_id, "relationship")
597 }
598
599 pub fn pending_commit_ts(&self) -> u64 {
600 self.write_ts.load(Ordering::Acquire)
601 }
602
603 pub fn take_redo(&self) -> Vec<RedoOp> {
604 std::mem::take(&mut *self.pending_redo.lock().unwrap())
605 }
606
607 fn end_write(&self, commit_ts: u64) {
611 self.set_commit_ts(commit_ts);
612 self.close_window();
613 self.close_restoring();
614 }
615
616 fn close_window(&self) {
621 self.in_write.store(false, Ordering::Release);
622 self.pending_redo.lock().unwrap().clear();
623 }
624
625 pub fn commit_write(&self) {
627 self.end_write(self.write_ts.load(Ordering::Acquire));
628 }
629
630 pub fn abort_write(&self) {
631 let ts = self.write_ts.load(Ordering::Acquire);
632 self.nodes.retain(|_, vers| vers.abort(ts));
633 self.rels.retain(|_, vers| vers.abort(ts));
634 self.close_window();
635 self.rebuild_adj();
636 self.rebuild_indexes();
637 }
638
639 pub fn reset_stats(&self) {
640 *self.stats.lock().unwrap() = QueryStats::default();
641 }
642
643 pub fn node_at(&self, id: NodeId, ts: u64) -> Option<Node> {
644 self.nodes
645 .get(&id)
646 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_node(id, &self.interner)))
647 }
648
649 pub fn node_labels_at(&self, id: NodeId, ts: u64) -> Option<Vec<String>> {
653 self.nodes.get(&id).and_then(|vers| {
654 visible_version(&vers, ts).map(|v| v.live.label_strings(&self.interner))
655 })
656 }
657
658 pub fn rel_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
659 self.rels
660 .get(&id)
661 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_rel(id, &self.interner)))
662 }
663
664 pub fn rel_ends_at(&self, id: RelId, ts: u64) -> Option<(NodeId, NodeId)> {
666 self.rels
667 .get(&id)
668 .and_then(|vers| visible_version(&vers, ts).map(|v| (v.live.start, v.live.end)))
669 }
670
671 fn rel_live_identity(&self, id: RelId) -> Option<(NodeId, NodeId, u32)> {
681 self.rels.get(&id).and_then(|vers| {
682 live_version(&vers).map(|v| (v.live.start, v.live.end, v.live.type_id))
683 })
684 }
685
686 pub fn node_stub_at(&self, id: NodeId, ts: u64) -> Option<Node> {
687 self.nodes
688 .get(&id)
689 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id, &self.interner)))
690 }
691
692 pub fn rel_stub_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
693 self.rels
694 .get(&id)
695 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id)))
696 }
697
698 pub fn node_prop_at(&self, id: NodeId, ts: u64, key: &str) -> Option<Value> {
699 self.nodes.get(&id).and_then(|vers| {
700 visible_version(&vers, ts).and_then(|v| v.live.prop(&self.interner, key))
701 })
702 }
703
704 pub fn rel_prop_at(&self, id: RelId, ts: u64, key: &str) -> Option<Value> {
705 self.rels.get(&id).and_then(|vers| {
706 visible_version(&vers, ts).and_then(|v| v.live.payload.get(&self.interner, key))
707 })
708 }
709
710 pub fn node_prop_keys_at(&self, id: NodeId, ts: u64) -> Vec<String> {
711 self.nodes
712 .get(&id)
713 .and_then(|vers| {
714 visible_version(&vers, ts).map(|v| v.live.props.keys_as_strings(&self.interner))
715 })
716 .unwrap_or_default()
717 }
718
719 pub fn rel_prop_keys_at(&self, id: RelId, ts: u64) -> Vec<String> {
720 self.rels
721 .get(&id)
722 .and_then(|vers| {
723 visible_version(&vers, ts).map(|v| v.live.payload.keys(&self.interner))
724 })
725 .unwrap_or_default()
726 }
727
728 pub(crate) fn rel_visible_at(&self, id: RelId, ts: u64) -> bool {
729 self.rels
730 .get(&id)
731 .is_some_and(|vers| visible_version(&vers, ts).is_some())
732 }
733
734 pub fn node(&self, id: NodeId) -> Option<Node> {
735 self.node_at(id, self.read_ts())
736 }
737
738 pub fn rel(&self, id: RelId) -> Option<Relationship> {
739 self.rel_at(id, self.read_ts())
740 }
741
742 fn visible_rel_account(&self, id: RelId) -> u64 {
745 let ts = self.read_ts();
746 self.rels
747 .get(&id)
748 .and_then(|vers| {
749 visible_version(&vers, ts).map(|v| crate::memory::live_rel_account_live(v.live))
750 })
751 .unwrap_or(0)
752 }
753
754 fn rel_form(&self, id: RelId) -> Option<crate::store::PayloadForm> {
755 let ts = self.read_ts();
756 self.rels.get(&id).and_then(|vers| {
757 visible_version(&vers, ts).map(|v| v.live.payload.form(&self.interner))
758 })
759 }
760
761 pub fn node_exists(&self, id: NodeId) -> bool {
762 self.node_visible_at(id, self.read_ts())
763 }
764
765 pub fn rel_exists(&self, id: RelId) -> bool {
766 self.rel_visible_at(id, self.read_ts())
767 }
768
769 pub fn live_node_count(&self) -> usize {
770 self.all_node_ids().len()
771 }
772
773 fn recording(&self) -> bool {
775 self.in_write.load(Ordering::Acquire) && self.record_redo.load(Ordering::Acquire)
776 }
777
778 fn push_redo(&self, op: RedoOp) {
779 if self.recording() {
780 self.pending_redo.lock().unwrap().push(op);
781 }
782 }
783
784 fn bump_stats(&self, f: impl FnOnce(&mut QueryStats)) {
785 f(&mut self.stats.lock().unwrap());
786 }
787
788 fn xmin_for_install(&self) -> u64 {
789 if self.in_write.load(Ordering::Acquire) {
790 self.write_ts.load(Ordering::Acquire)
791 } else {
792 let ts = self.commit_ts();
793 if ts == 0 {
794 self.set_commit_ts(1);
795 1
796 } else {
797 ts
798 }
799 }
800 }
801}
802
803pub(crate) fn spec_has_property_defaults(spec: &crate::graph_type::GraphTypeSpec) -> bool {
812 let identifying: std::collections::BTreeSet<&str> = spec
813 .node_types
814 .iter()
815 .map(|n| n.identifying_label.as_str())
816 .collect();
817 spec.node_types.iter().any(|n| {
818 n.properties.iter().any(|p| p.default_value.is_some())
819 || n.implied_labels
820 .iter()
821 .any(|l| identifying.contains(l.as_str()))
822 }) || spec
823 .edge_types
824 .iter()
825 .any(|e| e.properties.iter().any(|p| p.default_value.is_some()))
826}
827
828impl Graph {
829 pub(crate) fn selects(wanted: Option<u32>, label: u32) -> bool {
832 wanted.is_none_or(|wanted| wanted == label)
833 }
834
835 pub(crate) fn selects_type(wanted: Option<&[u32]>, type_id: u32) -> bool {
838 wanted.is_none_or(|wanted| wanted.contains(&type_id))
839 }
840
841 pub(crate) fn node_visible_at(&self, id: NodeId, ts: u64) -> bool {
842 self.nodes
843 .get(&id)
844 .is_some_and(|vers| visible_version(&vers, ts).is_some())
845 }
846}
847
848#[cfg(test)]
849mod tests;