use std::hash::{BuildHasherDefault, Hasher};
#[derive(Default, Clone, Copy)]
struct IdHasher(u64);
impl Hasher for IdHasher {
#[inline]
fn finish(&self) -> u64 {
let x = self.0;
let folded = x ^ (x >> 16) ^ (x >> 32) ^ (x >> 48);
folded | (folded << 57)
}
#[inline]
fn write_u64(&mut self, n: u64) {
self.0 = n;
}
fn write(&mut self, bytes: &[u8]) {
for &byte in bytes {
self.0 = self.0.rotate_left(8) ^ u64::from(byte);
}
}
}
type IdMap<V> = std::collections::HashMap<NodeId, V, BuildHasherDefault<IdHasher>>;
use std::{collections::hash_map::Entry, error::Error, fmt};
mod workspace;
pub use workspace::BfsWorkspace;
mod cluster_forest;
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)]
#[non_exhaustive]
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)]
#[non_exhaustive]
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: IdMap<usize>,
nodes: Option<Vec<NodeId>>,
adjacency: Vec<Vec<usize>>,
edges: usize,
}
const MIN_ROUND: usize = 1024;
const FIRST_ROUND: usize = 4;
const RETAIN_QUEUE: usize = 1 << 13;
const RETAIN_MARK_WORDS: usize = 1 << 14;
const SOURCE: u64 = 0b01;
const TARGET: u64 = 0b10;
#[inline]
fn mark_shift(vertex: usize) -> u32 {
((vertex & 31) * 2) as u32
}
#[derive(Default)]
struct Scratch {
marks: Vec<u64>,
source: Vec<usize>,
target: Vec<usize>,
dirty: bool,
}
impl Scratch {
fn reset(&mut self) {
if self.source.len() + self.target.len() > self.marks.len() {
self.marks.fill(0);
} else {
for &vertex in self.source.iter().chain(&self.target) {
self.marks[vertex >> 5] &= !(0b11 << mark_shift(vertex));
}
}
for queue in [&mut self.source, &mut self.target] {
queue.clear();
if queue.capacity() > RETAIN_QUEUE {
*queue = Vec::new();
}
}
if self.marks.len() > RETAIN_MARK_WORDS {
self.marks = Vec::new();
}
}
}
thread_local! {
static SCRATCH: std::cell::RefCell<Scratch> = std::cell::RefCell::new(Scratch::default());
}
struct SearchSide<'s> {
queue: &'s mut Vec<usize>,
own: u64,
cursor: usize,
pending: Option<usize>,
}
impl<'s> SearchSide<'s> {
fn new(queue: &'s mut Vec<usize>, marks: &mut [u64], endpoint: usize, own: u64) -> Self {
marks[endpoint >> 5] |= own << mark_shift(endpoint);
queue.push(endpoint);
Self {
queue,
own,
cursor: 0,
pending: None,
}
}
fn pending_degree(&mut self, adjacency: &[Vec<usize>]) -> usize {
*self.pending.get_or_insert_with(|| {
self.queue[self.cursor..]
.iter()
.map(|&vertex| adjacency[vertex].len())
.sum()
})
}
fn expand(
&mut self,
adjacency: &[Vec<usize>],
marks: &mut [u64],
pending: usize,
floor: usize,
) -> Option<bool> {
self.pending = None;
expand_round(
adjacency,
marks,
self.own,
self.queue,
&mut self.cursor,
pending.max(floor),
)
}
}
fn expand_round(
adjacency: &[Vec<usize>],
marks: &mut [u64],
own: u64,
queue: &mut Vec<usize>,
cursor_out: &mut usize,
budget: usize,
) -> Option<bool> {
let mut cursor = *cursor_out;
let mut examined = 0;
let outcome = loop {
let Some(&vertex) = queue.get(cursor) else {
break Some(false);
};
let neighbors = &adjacency[vertex];
if examined > 0 && examined + neighbors.len() > budget {
break None;
}
cursor += 1;
examined += neighbors.len();
let mut met = false;
for &neighbor in neighbors {
let word = &mut marks[neighbor >> 5];
let shift = mark_shift(neighbor);
let bits = (*word >> shift) & 0b11;
if bits == 0 {
*word |= own << shift;
queue.push(neighbor);
} else if bits != own {
met = true;
break;
}
}
if met {
break Some(true);
}
};
*cursor_out = cursor;
outcome
}
pub(crate) fn ids_by_index(
entries: impl Iterator<Item = (NodeId, usize)>,
len: usize,
) -> Vec<NodeId> {
let mut nodes = vec![0; len];
for (node, index) in entries {
nodes[index] = node;
}
nodes
}
pub(crate) fn visit_index_edges(
ids: impl Iterator<Item = (NodeId, usize)>,
len: usize,
edges: impl Iterator<Item = (usize, usize)>,
mut visit: impl FnMut(NodeId, NodeId),
) {
let nodes = ids_by_index(ids, len);
for (a, b) in edges {
let (a, b) = (nodes[a], nodes[b]);
visit(a.min(b), a.max(b));
}
}
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);
}
Ok(SCRATCH.with(|cell| match cell.try_borrow_mut() {
Ok(mut scratch) => self.search(&mut scratch, a, b),
Err(_) => self.search(&mut Scratch::default(), a, b),
}))
}
fn search(&self, scratch: &mut Scratch, a: usize, b: usize) -> bool {
if scratch.dirty {
*scratch = Scratch::default();
}
scratch.dirty = true;
let words = self.adjacency.len().div_ceil(32);
if scratch.marks.len() < words {
scratch.marks.resize(words, 0);
}
let found = {
let Scratch {
marks,
source,
target,
..
} = &mut *scratch;
let mut source_side = SearchSide::new(source, marks, a, SOURCE);
let mut target_side = SearchSide::new(target, marks, b, TARGET);
let mut floor = FIRST_ROUND;
loop {
let source_pending = source_side.pending_degree(&self.adjacency);
let target_pending = target_side.pending_degree(&self.adjacency);
let outcome = if target_pending < source_pending {
target_side.expand(&self.adjacency, marks, target_pending, floor)
} else {
source_side.expand(&self.adjacency, marks, source_pending, floor)
};
if let Some(found) = outcome {
break found;
}
floor = (floor * 2).min(MIN_ROUND);
}
};
scratch.reset();
scratch.dirty = false;
found
}
#[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: IdMap<usize> = IdMap::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 for_each_node(&self, mut visit: impl FnMut(NodeId)) {
self.ids.keys().for_each(|&node| visit(node));
}
pub(crate) fn for_each_edge(&self, mut visit: impl FnMut(NodeId, NodeId)) {
let built;
let nodes = match &self.nodes {
Some(nodes) => nodes.as_slice(),
None => {
built = ids_by_index(
self.ids.iter().map(|(&node, &index)| (node, index)),
self.adjacency.len(),
);
built.as_slice()
}
};
for (index, list) in self.adjacency.iter().enumerate() {
let node = nodes[index];
for &neighbor in &list[list.partition_point(|&other| other <= index)..] {
let other = nodes[neighbor];
visit(node.min(other), node.max(other));
}
}
}
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 scratch_reset_clears_marks_and_enforces_caps() {
let mut scratch = Scratch::default();
scratch.marks.resize(1_000, 0);
scratch.marks[0] |= SOURCE << mark_shift(3);
scratch.marks[1] |= TARGET << mark_shift(40);
scratch.source.push(3);
scratch.target.push(40);
scratch.reset();
assert_eq!(scratch.marks.len(), 1_000);
assert!(scratch.marks.iter().all(|&word| word == 0));
assert!(scratch.source.is_empty() && scratch.target.is_empty());
scratch.marks.resize(RETAIN_MARK_WORDS + 1, 0);
scratch.source.reserve(RETAIN_QUEUE + 1);
scratch.target.reserve(RETAIN_QUEUE + 1);
for vertex in 0..RETAIN_QUEUE {
scratch.marks[vertex >> 5] |= SOURCE << mark_shift(vertex);
scratch.source.push(vertex);
}
scratch.reset();
assert_eq!(
(
scratch.marks.len(),
scratch.source.capacity(),
scratch.target.capacity()
),
(0, 0, 0)
);
}
#[test]
fn mark_shift_gives_each_vertex_of_a_word_its_own_pair() {
let shifts: Vec<u32> = (0..32).map(mark_shift).collect();
assert_eq!(shifts, (0..32).map(|i| i * 2).collect::<Vec<_>>());
assert_eq!(mark_shift(32), 0);
assert_eq!(mark_shift(63), 62);
}
#[test]
fn id_hasher_folds_high_bits_and_tags_low_bits() {
let hash = |id: u64| {
let mut hasher = IdHasher::default();
hasher.write_u64(id);
hasher.finish()
};
let low = |h: u64| h & ((1 << 57) - 1);
assert_eq!(
(0..100).map(|i| low(hash(i))).collect::<Vec<_>>(),
(0..100).collect::<Vec<_>>()
);
for shift in [16, 32, 48] {
let buckets: std::collections::HashSet<u64> =
(0..1_000).map(|i| low(hash(i << shift)) & 0xFFFF).collect();
assert_eq!(buckets.len(), 1_000, "shift {shift}");
}
assert_eq!(hash(5) >> 57, 5);
assert_eq!(hash(130) >> 57, 2);
let mut bytes = IdHasher::default();
bytes.write(&[1, 2]);
assert_eq!(bytes.0, 0x0102);
}
#[test]
fn dirty_scratch_is_replaced_before_the_next_query() {
let mut graph = Graph::new();
graph.link(0, 1).unwrap();
graph.link(2, 3).unwrap();
SCRATCH.with(|cell| {
let mut scratch = cell.borrow_mut();
scratch.dirty = true;
scratch.marks = vec![u64::MAX];
scratch.source.push(1);
});
assert!(!graph.connected(0, 3).unwrap());
assert!(graph.connected(2, 3).unwrap());
SCRATCH.with(|cell| {
let scratch = cell.borrow();
assert!(!scratch.dirty);
assert!(scratch.marks.iter().all(|&word| word == 0));
assert!(scratch.source.is_empty() && scratch.target.is_empty());
});
}
#[test]
fn query_with_borrowed_thread_scratch_uses_private_scratch() {
let mut graph = Graph::new();
graph.link(0, 1).unwrap();
graph.link(1, 2).unwrap();
graph.link(5, 6).unwrap();
SCRATCH.with(|cell| {
let _held = cell.borrow_mut();
assert!(graph.connected(0, 2).unwrap());
assert!(!graph.connected(0, 6).unwrap());
});
}
#[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]);
}
}