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::{SealedArena, TypedAdj};
9use crate::group_key::GroupKey;
10use crate::memory::ChainShape;
11use crate::pull_identity::PullIdentityIndex;
12use crate::redo::{self, RedoOp};
13use crate::store::{Interner, LiveNode, LiveRel, RelTypes};
14
15use constraint_keys::ConstraintKeyIndex;
16use count_state::{CountDelta, CountStats};
17
18pub(crate) use count_state::{CountProbe, LabelSetCount};
21
22macro_rules! atomic_fetch_update {
27 ($atom:expr, $set:expr, $fetch:expr, $f:expr) => {{
28 #[allow(
29 deprecated,
30 reason = "fetch_update renamed to try_update in 1.99; try_update needs 1.95, MSRV is 1.88"
31 )]
32 {
33 $atom.fetch_update($set, $fetch, $f)
34 }
35 }};
36}
37
38mod access;
39mod accounting;
40#[cfg(any(test, feature = "test-hooks"))]
41mod build_counter;
42mod engine_api;
43
44mod adjacency;
45mod apply_redo;
46#[cfg(feature = "research")]
50pub(crate) mod census;
51mod chain;
52mod conflict;
53pub(crate) mod constraint_keys;
54mod count_state;
55mod declared;
56mod degree_stats;
57mod degree_stats_estimate;
58mod degree_stats_incident;
59mod derived_migration;
60mod entity_mutation;
61mod id_vec;
62mod index;
63mod index_lookup;
64mod index_postings;
65mod label_mutation;
66mod label_probe;
67mod pin;
68mod prop_read;
69mod query_stats;
70pub use pin::SnapshotPin;
71#[cfg(test)]
72use pin::PIN_ACQUIRE_RETRIES;
73#[cfg(test)]
74use pin::PIN_CLAIMING;
75use pin::{PIN_FREE, PIN_SLOTS};
76mod rebuild;
77mod redo_preflight;
78mod rel_postings;
79mod restore;
80mod schema_api;
81mod services;
82mod shard;
83#[cfg(feature = "research")]
87pub mod sol;
88#[cfg(feature = "research")]
92mod research;
93#[cfg(test)]
94pub(crate) mod test_support;
95mod theater;
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;
119pub use relate_planner::ContainsCount;
120pub(crate) use services::StoreServices;
121
122use theater::TheaterData;
123
124pub(crate) type CoreMap<K, V> = dashmap::DashMap<K, V, crate::hash_seed::FxBuildHasher>;
129
130impl relate_names::TokenResolver for Graph {
134 fn resolve(&self, name: &str) -> relate_names::Token {
135 self.interner.resolve(name)
136 }
137}
138
139impl Graph {
140 pub(in crate::graph) fn live_label_ids(&self, node: NodeId) -> Vec<u32> {
148 self.nodes
149 .get(&node)
150 .and_then(|vers| vers.live().map(|v| v.live.labels.clone()))
151 .unwrap_or_default()
152 }
153}
154
155pub(crate) use theater::{apply_show_overlay, DatabasesCatalog, ShowSchema};
156pub use theater::{CheckpointTheater, DatabaseEntry, SchemaSnapshot};
157
158pub(crate) trait ExhaustibleIdCounter {
163 fn try_alloc_id(&self) -> std::result::Result<i64, i64>;
164}
165
166impl ExhaustibleIdCounter for AtomicI64 {
167 fn try_alloc_id(&self) -> std::result::Result<i64, i64> {
168 atomic_fetch_update!(self, Ordering::Relaxed, Ordering::Relaxed, |id| {
169 if (0..i64::MAX).contains(&id) {
170 Some(id + 1)
171 } else {
172 None
173 }
174 })
175 }
176}
177
178impl ExhaustibleIdCounter for AtomicU64 {
179 fn try_alloc_id(&self) -> std::result::Result<i64, i64> {
180 atomic_fetch_update!(self, Ordering::Relaxed, Ordering::Relaxed, |id| {
181 (id < i64::MAX as u64).then_some(id + 1)
182 })
183 .map(|id| id as i64)
184 .map_err(|id| id as i64)
185 }
186}
187
188pub(crate) fn delete_connected_node_error() -> relate_core::Error {
196 relate_core::Error::execution(format!(
197 "{}: DeleteConnectedNode: Cannot delete node with relationships unless DETACH",
198 relate_error::NestedErrorClass::ConstraintVerificationFailed.as_str(),
199 ))
200}
201
202pub(crate) fn missing_rel_endpoint_error() -> relate_core::Error {
206 relate_core::Error::semantic("cannot create relationship on missing node")
207}
208
209pub(crate) fn alloc_exhaustible_id(counter: &impl ExhaustibleIdCounter, what: &str) -> Result<i64> {
212 counter
213 .try_alloc_id()
214 .map_err(|_| relate_core::Error::execution(format!("{what} ID exhausted")))
215}
216
217#[derive(Debug, Clone, Default)]
218pub struct Procedure {
219 pub name: String,
220 pub arg_names: Vec<String>,
221 pub arg_types: Vec<String>,
223 pub yield_names: Vec<String>,
224 pub rows: Vec<BTreeMap<String, Value>>,
225}
226
227use access::{live_version, visible_version};
228use chain::{Chain, Ver};
229use id_vec::IdVec;
230
231type NodeVer = Ver<LiveNode>;
234type RelVer = Ver<LiveRel>;
235
236pub(crate) fn node_version_stride() -> u64 {
237 std::mem::size_of::<NodeVer>() as u64
238}
239
240pub(crate) fn rel_version_stride() -> u64 {
241 std::mem::size_of::<RelVer>() as u64
242}
243
244pub(crate) fn node_slot() -> u64 {
248 id_vec::slot::<Chain<LiveNode>>()
249}
250
251pub(crate) fn rel_slot() -> u64 {
252 id_vec::slot::<Chain<LiveRel>>()
253}
254
255pub(crate) fn adj_slot() -> u64 {
256 id_vec::slot::<TypedAdj>()
257}
258
259fn sealed_slot() -> u64 {
262 crate::adjacency::span_stride()
263}
264
265pub(crate) fn node_value() -> u64 {
266 std::mem::size_of::<Chain<LiveNode>>() as u64
267}
268
269pub(crate) fn rel_value() -> u64 {
270 std::mem::size_of::<Chain<LiveRel>>() as u64
271}
272
273fn adj_value() -> u64 {
274 std::mem::size_of::<TypedAdj>() as u64
275}
276
277fn cow<Live: Clone>(write_ts: &AtomicU64, map: &IdVec<Chain<Live>>, id: i64) -> Option<Live> {
279 let ts = write_ts.load(Ordering::Acquire);
280 map.get_mut(&id)?.cow(ts)
281}
282
283#[derive(Debug)]
284pub struct Graph {
285 namespace: Namespace,
290 services: Arc<StoreServices>,
300 next_node_id: AtomicI64,
301 next_rel_id: AtomicI64,
302 published_ts: AtomicU64,
304 write_ts: AtomicU64,
305 in_write: AtomicBool,
306 restoring: AtomicBool,
314 record_redo: AtomicBool,
315 nodes: IdVec<Chain<LiveNode>>,
316 rels: IdVec<Chain<LiveRel>>,
317 out_adj: IdVec<TypedAdj>,
318 in_adj: IdVec<TypedAdj>,
319 sealed_out: SealedArena,
325 sealed_in: SealedArena,
326 count_stats: Mutex<CountStats>,
337 degree_histograms: Mutex<degree_stats::DegreeHistograms>,
351 constraint_keys: Mutex<ConstraintKeyIndex>,
361 interner: Interner,
362 catalog: Mutex<Catalog>,
363 pub(crate) theater: Mutex<TheaterData>,
364 legacy_unenforced: Mutex<HashMap<String, ConstraintDef>>,
366 stats: Mutex<QueryStats>,
367 indexes: Indexes,
371 contains_memo: Mutex<ContainsMemo>,
378 pending_redo: Mutex<Vec<RedoOp>>,
379 pull_identity: PullIdentityIndex,
381 dirty_nodes: Mutex<HashSet<NodeId>>,
383 dirty_rels: Mutex<HashSet<RelId>>,
384 pins: Box<[AtomicU64]>,
386 pin_cursor: AtomicU64,
387 used_bytes: AtomicU64,
389}
390
391impl Default for Graph {
392 fn default() -> Self {
393 let interner = Interner::default();
394 let indexes = Indexes::new(&interner);
395 Self {
396 namespace: Namespace::Neo4j,
397 services: Arc::new(StoreServices::default()),
398 next_node_id: AtomicI64::new(0),
399 next_rel_id: AtomicI64::new(0),
400 published_ts: AtomicU64::new(0),
401 write_ts: AtomicU64::new(0),
402 in_write: AtomicBool::new(false),
403 restoring: AtomicBool::new(true),
404 record_redo: AtomicBool::new(true),
405 nodes: IdVec::default(),
406 rels: IdVec::default(),
407 out_adj: IdVec::default(),
408 in_adj: IdVec::default(),
409 sealed_out: SealedArena::default(),
410 sealed_in: SealedArena::default(),
411 count_stats: Mutex::new(CountStats::default()),
412 degree_histograms: Mutex::new(degree_stats::DegreeHistograms::default()),
413 constraint_keys: Mutex::new(ConstraintKeyIndex::default()),
414 interner,
415 catalog: Mutex::new(Catalog::default()),
416 theater: Mutex::new(TheaterData::default()),
417 indexes,
418 contains_memo: Mutex::new(ContainsMemo::default()),
419 legacy_unenforced: Mutex::new(HashMap::new()),
420 stats: Mutex::new(QueryStats::default()),
421 pending_redo: Mutex::new(Vec::new()),
422 pull_identity: PullIdentityIndex::default(),
423 dirty_nodes: Mutex::new(HashSet::new()),
424 dirty_rels: Mutex::new(HashSet::new()),
425 pins: (0..PIN_SLOTS).map(|_| AtomicU64::new(PIN_FREE)).collect(),
426 pin_cursor: AtomicU64::new(0),
427 used_bytes: AtomicU64::new(0),
428 }
429 }
430}
431
432fn visible(xmin: u64, xmax: u64, ts: u64) -> bool {
433 xmin != 0 && xmin <= ts && (xmax == 0 || xmax > ts)
434}
435
436fn checked_persisted_id(id: i64, what: &str) -> Result<i64> {
437 relate_core::validate_persisted_id(id, what)?;
438 Ok(id + 1)
439}
440
441fn requires_enforced_label(def: &ConstraintDef) -> bool {
442 def.kind
443 .parse::<relate_model::ConstraintType>()
444 .is_ok_and(|kind| kind.is_enforced_label_kind())
445}
446
447fn matching_enforced_label(def: &ConstraintDef, c: &relate_model::Constraint) -> bool {
448 c.label == def.label
449 && c.properties == def.properties
450 && def.kind.parse::<relate_model::ConstraintType>() == Ok(c.constraint_type)
451 && c.property_type == def.property_type
452 && c.constraint_type
453 .enforced_label_site()
454 .is_some_and(|site| site.is_relationship() == def.relationship)
455 && c.enforced_label
456 .as_deref()
457 .is_some_and(|label| !label.is_empty())
458}
459
460fn has_enforced_label(c: &relate_model::Constraint) -> bool {
464 c.constraint_type.is_enforced_label_kind()
465 && c.enforced_label
466 .as_deref()
467 .is_some_and(|label| !label.is_empty())
468}
469
470impl Graph {
471 pub(crate) fn has_property_defaults(&self) -> bool {
477 let theater = self.theater.lock().expect("theater lock poisoned");
478 spec_has_property_defaults(&theater.current_graph_type)
479 }
480
481 pub fn namespace(&self) -> Namespace {
483 self.namespace
484 }
485
486 #[doc(hidden)]
489 pub fn set_namespace(&mut self, namespace: Namespace) {
490 self.namespace = namespace;
491 }
492
493 pub fn commit_ts(&self) -> u64 {
494 self.published_ts.load(Ordering::Acquire)
495 }
496
497 pub(crate) fn in_write_window(&self) -> bool {
503 self.in_write.load(Ordering::Acquire)
504 }
505
506 pub fn set_commit_ts(&self, ts: u64) {
507 self.published_ts.store(ts, Ordering::Release);
508 }
509
510 pub fn next_node_id(&self) -> NodeId {
511 self.next_node_id.load(Ordering::Relaxed)
512 }
513
514 pub fn set_next_node_id(&self, id: NodeId) {
515 self.next_node_id.store(id, Ordering::Relaxed);
516 }
517
518 pub fn next_rel_id(&self) -> RelId {
519 self.next_rel_id.load(Ordering::Relaxed)
520 }
521
522 fn mark_node_dirty(&self, id: NodeId) {
523 self.dirty_nodes.lock().unwrap().insert(id);
524 }
525
526 fn mark_rel_dirty(&self, id: RelId) {
527 self.dirty_rels.lock().unwrap().insert(id);
528 }
529
530 pub fn set_next_rel_id(&self, id: RelId) {
531 self.next_rel_id.store(id, Ordering::Relaxed);
532 }
533
534 fn read_ts(&self) -> u64 {
535 if self.in_write.load(Ordering::Acquire) {
536 self.write_ts.load(Ordering::Acquire)
537 } else {
538 self.commit_ts()
539 }
540 }
541
542 pub fn begin_write(&self) -> Result<()> {
545 let ts = self
546 .commit_ts()
547 .checked_add(1)
548 .filter(|ts| *ts < u64::MAX)
549 .ok_or_else(|| relate_core::Error::execution("write timestamp exhausted"))?;
550 self.begin_write_at(ts)
551 }
552
553 pub fn begin_write_at(&self, write_ts: u64) -> Result<()> {
556 if write_ts == u64::MAX {
557 return Err(relate_core::Error::execution("write timestamp exhausted"));
558 }
559 self.in_write.store(true, Ordering::Release);
560 self.write_ts.store(write_ts, Ordering::Release);
561 self.pending_redo.lock().unwrap().clear();
562 self.record_redo.store(true, Ordering::Release);
563 self.reset_stats();
564 Ok(())
565 }
566
567 fn alloc_node_id(&self) -> Result<NodeId> {
568 alloc_exhaustible_id(&self.next_node_id, "node")
569 }
570
571 fn alloc_rel_id(&self) -> Result<RelId> {
572 alloc_exhaustible_id(&self.next_rel_id, "relationship")
573 }
574
575 pub fn pending_commit_ts(&self) -> u64 {
576 self.write_ts.load(Ordering::Acquire)
577 }
578
579 pub fn take_redo(&self) -> Vec<RedoOp> {
580 std::mem::take(&mut *self.pending_redo.lock().unwrap())
581 }
582
583 fn end_write(&self, commit_ts: u64) {
587 self.set_commit_ts(commit_ts);
588 self.close_window();
589 self.close_restoring();
590 }
591
592 fn close_window(&self) {
597 self.in_write.store(false, Ordering::Release);
598 self.pending_redo.lock().unwrap().clear();
599 }
600
601 pub fn commit_write(&self) {
603 self.end_write(self.write_ts.load(Ordering::Acquire));
604 }
605
606 pub fn abort_write(&self) {
607 let ts = self.write_ts.load(Ordering::Acquire);
608 self.nodes.retain(|_, vers| vers.abort(ts));
609 self.rels.retain(|_, vers| vers.abort(ts));
610 self.close_window();
611 self.rebuild_adj();
612 self.rebuild_indexes();
613 }
614
615 pub fn reset_stats(&self) {
616 *self.stats.lock().unwrap() = QueryStats::default();
617 }
618
619 pub fn node_at(&self, id: NodeId, ts: u64) -> Option<Node> {
620 self.nodes
621 .get(&id)
622 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_node(id, &self.interner)))
623 }
624
625 pub fn node_labels_at(&self, id: NodeId, ts: u64) -> Option<Vec<String>> {
629 self.nodes.get(&id).and_then(|vers| {
630 visible_version(&vers, ts).map(|v| v.live.label_strings(&self.interner))
631 })
632 }
633
634 pub fn rel_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
635 self.rels
636 .get(&id)
637 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.to_rel(id, &self.interner)))
638 }
639
640 pub fn rel_ends_at(&self, id: RelId, ts: u64) -> Option<(NodeId, NodeId)> {
642 self.rels
643 .get(&id)
644 .and_then(|vers| visible_version(&vers, ts).map(|v| (v.live.start, v.live.end)))
645 }
646
647 fn rel_live_identity(&self, id: RelId) -> Option<(NodeId, NodeId, u32)> {
657 self.rels.get(&id).and_then(|vers| {
658 live_version(&vers).map(|v| (v.live.start, v.live.end, v.live.type_id))
659 })
660 }
661
662 pub fn node_stub_at(&self, id: NodeId, ts: u64) -> Option<Node> {
663 self.nodes
664 .get(&id)
665 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id, &self.interner)))
666 }
667
668 pub fn rel_stub_at(&self, id: RelId, ts: u64) -> Option<Relationship> {
669 self.rels
670 .get(&id)
671 .and_then(|vers| visible_version(&vers, ts).map(|v| v.live.stub(id)))
672 }
673
674 pub fn node_prop_at(&self, id: NodeId, ts: u64, key: &str) -> Option<Value> {
675 self.nodes.get(&id).and_then(|vers| {
676 visible_version(&vers, ts).and_then(|v| v.live.prop(&self.interner, key))
677 })
678 }
679
680 pub fn rel_prop_at(&self, id: RelId, ts: u64, key: &str) -> Option<Value> {
681 self.rels.get(&id).and_then(|vers| {
682 visible_version(&vers, ts).and_then(|v| v.live.payload.get(&self.interner, key))
683 })
684 }
685
686 pub fn node_prop_keys_at(&self, id: NodeId, ts: u64) -> Vec<String> {
687 self.nodes
688 .get(&id)
689 .and_then(|vers| {
690 visible_version(&vers, ts).map(|v| v.live.props.keys_as_strings(&self.interner))
691 })
692 .unwrap_or_default()
693 }
694
695 pub fn rel_prop_keys_at(&self, id: RelId, ts: u64) -> Vec<String> {
696 self.rels
697 .get(&id)
698 .and_then(|vers| {
699 visible_version(&vers, ts).map(|v| v.live.payload.keys(&self.interner))
700 })
701 .unwrap_or_default()
702 }
703
704 pub(crate) fn rel_visible_at(&self, id: RelId, ts: u64) -> bool {
705 self.rels
706 .get(&id)
707 .is_some_and(|vers| visible_version(&vers, ts).is_some())
708 }
709
710 pub fn node(&self, id: NodeId) -> Option<Node> {
711 self.node_at(id, self.read_ts())
712 }
713
714 pub fn rel(&self, id: RelId) -> Option<Relationship> {
715 self.rel_at(id, self.read_ts())
716 }
717
718 fn visible_rel_account(&self, id: RelId) -> u64 {
721 let ts = self.read_ts();
722 self.rels
723 .get(&id)
724 .and_then(|vers| {
725 visible_version(&vers, ts).map(|v| crate::memory::live_rel_account_live(v.live))
726 })
727 .unwrap_or(0)
728 }
729
730 fn rel_form(&self, id: RelId) -> Option<crate::store::PayloadForm> {
731 let ts = self.read_ts();
732 self.rels.get(&id).and_then(|vers| {
733 visible_version(&vers, ts).map(|v| v.live.payload.form(&self.interner))
734 })
735 }
736
737 pub fn node_exists(&self, id: NodeId) -> bool {
738 self.node_visible_at(id, self.read_ts())
739 }
740
741 pub fn rel_exists(&self, id: RelId) -> bool {
742 self.rel_visible_at(id, self.read_ts())
743 }
744
745 pub fn live_node_count(&self) -> usize {
746 self.all_node_ids().len()
747 }
748
749 fn recording(&self) -> bool {
751 self.in_write.load(Ordering::Acquire) && self.record_redo.load(Ordering::Acquire)
752 }
753
754 fn push_redo(&self, op: RedoOp) {
755 if self.recording() {
756 self.pending_redo.lock().unwrap().push(op);
757 }
758 }
759
760 fn bump_stats(&self, f: impl FnOnce(&mut QueryStats)) {
761 f(&mut self.stats.lock().unwrap());
762 }
763
764 fn xmin_for_install(&self) -> u64 {
765 if self.in_write.load(Ordering::Acquire) {
766 self.write_ts.load(Ordering::Acquire)
767 } else {
768 let ts = self.commit_ts();
769 if ts == 0 {
770 self.set_commit_ts(1);
771 1
772 } else {
773 ts
774 }
775 }
776 }
777}
778
779pub(crate) fn spec_has_property_defaults(spec: &crate::graph_type::GraphTypeSpec) -> bool {
788 let identifying: std::collections::BTreeSet<&str> = spec
789 .node_types
790 .iter()
791 .map(|n| n.identifying_label.as_str())
792 .collect();
793 spec.node_types.iter().any(|n| {
794 n.properties.iter().any(|p| p.default_value.is_some())
795 || n.implied_labels
796 .iter()
797 .any(|l| identifying.contains(l.as_str()))
798 }) || spec
799 .edge_types
800 .iter()
801 .any(|e| e.properties.iter().any(|p| p.default_value.is_some()))
802}
803
804impl Graph {
805 pub(crate) fn selects(wanted: Option<u32>, label: u32) -> bool {
808 wanted.is_none_or(|wanted| wanted == label)
809 }
810
811 pub(crate) fn selects_type(wanted: Option<&[u32]>, type_id: u32) -> bool {
814 wanted.is_none_or(|wanted| wanted.contains(&type_id))
815 }
816
817 pub(crate) fn node_visible_at(&self, id: NodeId, ts: u64) -> bool {
818 self.nodes
819 .get(&id)
820 .is_some_and(|vers| visible_version(&vers, ts).is_some())
821 }
822}
823
824#[cfg(test)]
825mod tests;