use fixedbitset::FixedBitSet;
use nohash_hasher::IntMap;
use std::{collections::hash_map::Entry, error::Error, fmt};
mod workspace;
pub use workspace::BfsWorkspace;
mod configuration;
mod dynamic;
mod forest;
mod hdt;
mod hdt_forest;
mod hdt_profile;
mod index;
pub use hdt::{HdtGraph, HdtStats};
pub use hdt_profile::{HdtLevelStorage, HdtStorageStats};
mod reference;
pub use configuration::{ConnectivityGraph, EngineConfig, GraphLimits};
pub use dynamic::{ForestGraph, ForestStats};
pub use reference::ReferenceGraph;
mod topology;
pub use topology::{
EdgeSpec, EdgeState, LifecycleError, LifecycleGraph, LifecycleStorage, NodeSpec,
};
pub type NodeId = u64;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GraphError {
NodeLimitExceeded {
limit: usize,
},
EdgeLimitExceeded {
limit: usize,
},
SelfLoop {
node: NodeId,
},
UnknownNode {
node: NodeId,
},
}
impl fmt::Display for GraphError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NodeLimitExceeded { limit } => write!(formatter, "node limit exceeded: {limit}"),
Self::EdgeLimitExceeded { limit } => write!(formatter, "edge limit exceeded: {limit}"),
Self::SelfLoop { node } => write!(formatter, "self-loops are not supported: {node}"),
Self::UnknownNode { node } => write!(formatter, "unknown node: {node}"),
}
}
}
impl GraphError {
#[inline]
pub(crate) fn check_distinct(source: NodeId, target: NodeId) -> Result<(), Self> {
if source == target {
Err(Self::SelfLoop { node: source })
} else {
Ok(())
}
}
}
impl Error for GraphError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IncidenceError {
UnknownNode,
UnknownCursor,
NotEnabled,
}
impl fmt::Display for IncidenceError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::UnknownNode => "unknown node",
Self::UnknownCursor => "unknown incidence cursor",
Self::NotEnabled => "neighbor listing is not enabled",
})
}
}
impl Error for IncidenceError {}
#[derive(Debug, Default)]
pub struct Graph {
ids: IntMap<NodeId, usize>,
nodes: Option<Vec<NodeId>>,
adjacency: Vec<Vec<usize>>,
edges: usize,
}
impl Graph {
pub(crate) fn contains_node(&self, node: NodeId) -> bool {
self.ids.contains_key(&node)
}
pub(crate) fn contains_edge(&self, source: NodeId, target: NodeId) -> bool {
let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
return false;
};
self.adjacency[a].binary_search(&b).is_ok()
}
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[inline]
fn get_or_insert_index(&mut self, node: NodeId) -> usize {
match self.ids.entry(node) {
Entry::Occupied(entry) => *entry.get(),
Entry::Vacant(entry) => {
let index = self.adjacency.len();
self.adjacency.push(Vec::new());
if let Some(nodes) = &mut self.nodes {
nodes.push(node);
}
entry.insert(index);
index
}
}
}
pub fn add_node(&mut self, node: NodeId) -> bool {
if let Entry::Vacant(entry) = self.ids.entry(node) {
let index = self.adjacency.len();
self.adjacency.push(Vec::new());
if let Some(nodes) = &mut self.nodes {
nodes.push(node);
}
entry.insert(index);
true
} else {
false
}
}
pub fn link(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
GraphError::check_distinct(source, target)?;
let a = self.get_or_insert_index(source);
let b = self.get_or_insert_index(target);
let Err(position) = self.adjacency[a].binary_search(&b) else {
return Ok(false);
};
let reverse = self.adjacency[b]
.binary_search(&a)
.expect_err("symmetric absence");
self.adjacency[a].insert(position, b);
self.adjacency[b].insert(reverse, a);
self.edges += 1;
Ok(true)
}
pub fn cut(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
GraphError::check_distinct(source, target)?;
let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
return Ok(false);
};
let Ok(position) = self.adjacency[a].binary_search(&b) else {
return Ok(false);
};
let reverse = self.adjacency[b].binary_search(&a).expect("symmetric edge");
self.adjacency[a].remove(position);
self.adjacency[b].remove(reverse);
self.edges -= 1;
Ok(true)
}
pub fn connected(&self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
let a = *self
.ids
.get(&source)
.ok_or(GraphError::UnknownNode { node: source })?;
let b = *self
.ids
.get(&target)
.ok_or(GraphError::UnknownNode { node: target })?;
if a == b {
return Ok(true);
}
let mut visited = FixedBitSet::with_capacity(self.adjacency.len());
let mut queue = Vec::new();
visited.insert(a);
queue.push(a);
let mut cursor = 0;
while cursor < queue.len() {
for &neighbor in &self.adjacency[queue[cursor]] {
if neighbor == b {
return Ok(true);
}
if !visited.contains(neighbor) {
visited.insert(neighbor);
queue.push(neighbor);
}
}
cursor += 1;
}
Ok(false)
}
#[must_use]
pub fn node_count(&self) -> usize {
self.adjacency.len()
}
#[must_use]
pub fn edge_count(&self) -> usize {
self.edges
}
pub(crate) fn from_sorted_adjacency(ids: Vec<NodeId>, adjacency: Vec<Vec<usize>>) -> Self {
assert_eq!(ids.len(), adjacency.len(), "one adjacency list per ID");
let mut map: IntMap<NodeId, usize> =
IntMap::with_capacity_and_hasher(ids.len(), Default::default());
for (index, &node) in ids.iter().enumerate() {
let previous = map.insert(node, index);
debug_assert!(previous.is_none(), "distinct IDs");
}
let incidences: usize = adjacency.iter().map(Vec::len).sum();
debug_assert!(incidences.is_multiple_of(2), "symmetric adjacency");
#[cfg(debug_assertions)]
for (index, list) in adjacency.iter().enumerate() {
for pair in list.windows(2) {
debug_assert!(pair[0] < pair[1], "strictly sorted adjacency");
}
for &neighbor in list {
debug_assert_ne!(neighbor, index, "no self-loops");
debug_assert!(
adjacency[neighbor].binary_search(&index).is_ok(),
"symmetric adjacency"
);
}
}
Self {
ids: map,
nodes: None,
adjacency,
edges: incidences / 2,
}
}
#[must_use]
pub fn degree(&self, node: NodeId) -> Option<usize> {
self.ids
.get(&node)
.map(|&index| self.adjacency[index].len())
}
pub fn enable_neighbor_listing(&mut self) {
if self.nodes.is_none() {
let mut nodes = vec![0; self.adjacency.len()];
for (&node, &index) in &self.ids {
nodes[index] = node;
}
self.nodes = Some(nodes);
}
}
pub fn neighbors_after(
&self,
node: NodeId,
after: Option<NodeId>,
) -> Result<impl Iterator<Item = NodeId> + '_, IncidenceError> {
let &index = self.ids.get(&node).ok_or(IncidenceError::UnknownNode)?;
let list = &self.adjacency[index];
let start = match after {
None => 0,
Some(cursor) => {
let &cursor = self.ids.get(&cursor).ok_or(IncidenceError::UnknownCursor)?;
list.partition_point(|&neighbor| neighbor <= cursor)
}
};
let nodes = self.nodes.as_deref().ok_or(IncidenceError::NotEnabled)?;
Ok(list[start..].iter().map(move |&neighbor| nodes[neighbor]))
}
pub(crate) fn release_isolated_storage(&mut self, node: NodeId) {
if let Some(&index) = self.ids.get(&node) {
let list = &mut self.adjacency[index];
if list.is_empty() {
*list = Vec::new();
}
}
}
#[cfg(test)]
pub(crate) fn adjacency_capacity(&self, node: NodeId) -> Option<usize> {
self.ids
.get(&node)
.map(|&index| self.adjacency[index].capacity())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn neighbor_pages_visit_stable_neighbors_exactly_once() {
let mut graph = Graph::new();
graph.link(0, 3).unwrap();
assert_eq!(
graph.neighbors_after(0, None).err(),
Some(IncidenceError::NotEnabled)
);
graph.enable_neighbor_listing();
graph.enable_neighbor_listing();
graph.cut(0, 3).unwrap();
for neighbor in 1..=100u64 {
graph.link(0, neighbor * 7).unwrap();
}
let stable: Vec<u64> = (1..=100u64).filter(|n| n % 3 != 0).map(|n| n * 7).collect();
let mut seen = Vec::new();
let mut cursor = None;
let mut round = 0u64;
loop {
let page: Vec<u64> = graph.neighbors_after(0, cursor).unwrap().take(9).collect();
let Some(&last) = page.last() else { break };
seen.extend(page);
cursor = Some(last);
for n in (1..=100u64).filter(|n| n % 3 == 0) {
let _ = graph.cut(0, n * 7);
}
if round < 5 {
round += 1;
graph.link(0, 10_000 + round).unwrap();
}
}
for node in &stable {
assert_eq!(seen.iter().filter(|&&s| s == *node).count(), 1, "{node}");
}
assert_eq!(graph.degree(0), Some(stable.len() + round as usize));
assert_eq!(graph.degree(424_242), None);
assert_eq!(
graph.neighbors_after(424_242, None).err(),
Some(IncidenceError::UnknownNode)
);
assert_eq!(
graph.neighbors_after(0, Some(424_242)).err(),
Some(IncidenceError::UnknownCursor)
);
assert_eq!(
IncidenceError::UnknownCursor.to_string(),
"unknown incidence cursor"
);
assert_eq!(IncidenceError::UnknownNode.to_string(), "unknown node");
assert_eq!(
IncidenceError::NotEnabled.to_string(),
"neighbor listing is not enabled"
);
}
#[test]
fn bulk_built_graph_lists_neighbors_by_id() {
let ids = vec![u64::MAX, 3, 9_007_199_254_740_993];
let adjacency = vec![vec![1, 2], vec![0], vec![0]];
let mut graph = Graph::from_sorted_adjacency(ids, adjacency);
graph.enable_neighbor_listing();
let neighbors: Vec<u64> = graph.neighbors_after(u64::MAX, None).unwrap().collect();
assert_eq!(neighbors, [3, 9_007_199_254_740_993]);
assert_eq!(graph.degree(3), Some(1));
}
#[test]
fn bulk_built_graph_matches_incremental_graph_under_mutation() {
let mut seed = 0x2545_f491_u64;
let mut next = move |bound: u64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed % bound
};
for _case in 0..200 {
let n = 1 + next(30) as usize;
let ids: Vec<NodeId> = (0..n as u64).map(|i| i * 7 + 3).collect();
let mut incremental = Graph::new();
for &id in &ids {
incremental.add_node(id);
}
let mut adjacency = vec![Vec::new(); n];
for _ in 0..next(3 * n as u64 + 1) {
let (a, b) = (next(n as u64) as usize, next(n as u64) as usize);
if a != b && incremental.link(ids[a], ids[b]) == Ok(true) {
adjacency[a].push(b);
adjacency[b].push(a);
}
}
for list in &mut adjacency {
list.sort_unstable();
}
let mut bulk = Graph::from_sorted_adjacency(ids.clone(), adjacency);
assert_eq!(bulk.node_count(), incremental.node_count());
assert_eq!(bulk.edge_count(), incremental.edge_count());
for _ in 0..100 {
let a = next(n as u64 + 5) * 7 + 3;
let b = next(n as u64 + 5) * 7 + 3;
match next(4) {
0 => assert_eq!(bulk.add_node(a), incremental.add_node(a)),
1 => assert_eq!(bulk.link(a, b), incremental.link(a, b)),
2 => assert_eq!(bulk.cut(a, b), incremental.cut(a, b)),
_ => assert_eq!(bulk.connected(a, b), incremental.connected(a, b)),
}
assert_eq!(bulk.edge_count(), incremental.edge_count());
assert_eq!(bulk.node_count(), incremental.node_count());
}
for list in &bulk.adjacency {
assert!(list.windows(2).all(|pair| pair[0] < pair[1]));
}
bulk.release_isolated_storage(ids[0]);
assert_eq!(bulk.connected(ids[0], ids[0]), Ok(true));
}
}
#[test]
fn link_preserves_internal_source_before_target_index_order() {
let mut graph = Graph::new();
assert_eq!(graph.link(42, 99), Ok(true));
assert_eq!(graph.ids.get(&42), Some(&0));
assert_eq!(graph.ids.get(&99), Some(&1));
assert_eq!(graph.adjacency[0], vec![1]);
assert_eq!(graph.adjacency[1], vec![0]);
assert_eq!(graph.link(42, 1000), Ok(true));
assert_eq!(graph.ids.get(&1000), Some(&2));
assert_eq!(graph.adjacency[0], vec![1, 2]);
assert_eq!(graph.adjacency[2], vec![0]);
assert_eq!(graph.link(2000, 99), Ok(true));
assert_eq!(graph.ids.get(&2000), Some(&3));
assert_eq!(graph.adjacency[1], vec![0, 3]);
assert_eq!(graph.adjacency[3], vec![1]);
assert_eq!(graph.link(1000, 2000), Ok(true));
assert_eq!(graph.ids.get(&1000), Some(&2));
assert_eq!(graph.ids.get(&2000), Some(&3));
assert_eq!(graph.adjacency[2], vec![0, 3]);
assert_eq!(graph.adjacency[3], vec![1, 2]);
}
}