use super::id_vec::IdVec;
use super::shard;
use super::*;
use crate::adjacency::{Hop, SealedRegion};
#[derive(Clone, Copy, Debug)]
pub(super) struct ChunkHops {
pub(super) type_id: u32,
pub(super) hops: usize,
}
#[derive(Clone, Copy)]
pub(super) struct AdjSide<'a> {
delta: &'a IdVec<TypedAdj>,
sealed: &'a SealedArena,
}
impl<'a> AdjSide<'a> {
pub(super) fn delta(&self) -> &'a IdVec<TypedAdj> {
self.delta
}
pub(super) fn sealed(&self) -> &'a SealedArena {
self.sealed
}
pub(super) fn with_adj<R>(
&self,
node: NodeId,
f: impl FnOnce(&TypedAdj, Option<SealedRegion<'_>>) -> R,
) -> Option<R> {
let adj = self.delta.get(&node)?;
let region = self.sealed.region(node);
Some(f(&adj, region))
}
fn clear(&self) {
self.delta.clear();
self.sealed.clear();
}
fn flatten(&self, node: NodeId) -> Vec<RelId> {
self.with_adj(node, |adj, region| adj.flatten(region))
.unwrap_or_default()
}
pub(super) fn floor(&self, node: NodeId) -> u64 {
self.delta.get(&node).map_or(0, |adj| adj.floor_bytes())
}
pub(super) fn hop_counts(&self, node: NodeId) -> Vec<ChunkHops> {
self.with_adj(node, |adj, region| {
adj.chunk_lens(region)
.map(|(type_id, delta, sealed)| ChunkHops {
type_id,
hops: delta + sealed,
})
.collect()
})
.unwrap_or_default()
}
pub(super) fn insert(&self, node: NodeId, type_id: u32, id: RelId, ts: Option<i64>) {
self.delta.entry(node).or_default().insert(type_id, id, ts);
}
pub(super) fn reposition(
&self,
node: NodeId,
type_id: u32,
id: RelId,
ts: Option<i64>,
xmax: u64,
) {
let mut adj_entry = self.delta.entry(node);
let region = self
.sealed
.region(node)
.filter(|region| region.has_chunk(type_id));
match region {
Some(region) => adj_entry
.or_default()
.reposition(region, type_id, id, ts, xmax),
None => {
let adj = adj_entry.or_default();
adj.remove(None, type_id, id);
adj.insert(type_id, id, ts);
}
}
}
pub(super) fn remove(&self, node: NodeId, type_id: u32, id: RelId) {
if let Some(mut adj) = self.delta.get_mut(&node) {
adj.remove(self.sealed.region(node), type_id, id);
}
self.delta.remove_if(&node, TypedAdj::is_empty);
}
pub(super) fn tombstone_deleted(&self, node: NodeId, type_id: u32, id: RelId, xmax: u64) {
self.sealed.tombstone_deleted(
node,
type_id,
id,
xmax,
crate::adjacency::Supersede::Deleted,
);
}
fn fold(&self, horizon: u64, gate: FoldGate) {
let mut due_nodes: Vec<(NodeId, Vec<u32>)> = Vec::new();
self.delta.for_each(|node, adj| {
let due = gate.due(adj, self.sealed.region(node), horizon);
if !due.is_empty() {
due_nodes.push((node, due));
}
});
for (node, due) in due_nodes {
let Some(mut adj) = self.delta.get_mut(&node) else {
continue;
};
adj.fold_due(
self.sealed.region_or_default(node),
&due,
horizon,
gate.floor(),
);
}
}
fn len(&self, node: NodeId) -> usize {
self.with_adj(node, |adj, region| {
adj.chunk_lens(region)
.map(|(_, delta, sealed)| delta + sealed)
.sum()
})
.unwrap_or(0)
}
fn typed_len(&self, node: NodeId, type_ids: impl Iterator<Item = u32>) -> usize {
self.with_adj(node, |adj, region| {
type_ids.map(|type_id| adj.total_len(region, type_id)).sum()
})
.unwrap_or(0)
}
}
impl Graph {
pub(super) fn out_side(&self) -> AdjSide<'_> {
AdjSide {
delta: &self.out_adj,
sealed: &self.sealed_out,
}
}
pub(super) fn sides(
&self,
dir: relate_ir::Direction,
) -> impl Iterator<Item = (AdjSide<'_>, relate_ir::Direction)> {
use relate_ir::Direction;
[
(self.out_side(), Direction::Outgoing),
(self.in_side(), Direction::Incoming),
]
.into_iter()
.filter(move |&(_, scan_dir)| dir == Direction::Both || dir == scan_dir)
}
pub(super) fn in_side(&self) -> AdjSide<'_> {
AdjSide {
delta: &self.in_adj,
sealed: &self.sealed_in,
}
}
}
#[derive(Clone, Copy)]
pub enum Side {
Start,
End,
}
#[derive(Clone, Copy)]
enum FoldGate {
Watermark,
BuildSeal,
}
impl FoldGate {
fn due(&self, adj: &TypedAdj, sealed: Option<SealedRegion<'_>>, horizon: u64) -> Vec<u32> {
match self {
FoldGate::Watermark => adj.due_chunks(sealed, horizon),
FoldGate::BuildSeal => adj.sealable_chunks(),
}
}
fn floor(&self) -> usize {
match self {
FoldGate::Watermark => crate::adjacency::COMPACTION_DELTA_FLOOR,
FoldGate::BuildSeal => crate::adjacency::RESTORE_SEAL_HOPS,
}
}
}
impl Side {
fn endpoint(&self, row: &RelRow) -> NodeId {
match self {
Side::Start => row.start,
Side::End => row.end,
}
}
fn adj(self, graph: &Graph) -> AdjSide<'_> {
match self {
Side::Start => graph.out_side(),
Side::End => graph.in_side(),
}
}
}
fn build_side(graph: &Graph, rows: &[RelRow], side: Side, shards: &[Vec<usize>]) {
let adjacency = side.adj(graph);
adjacency.clear();
let parts = shard::run_shards(shards, |shard| {
build_shard(rows, shard, side, adjacency.sealed)
});
for (node, adj) in parts.into_iter().flatten() {
adjacency.delta.insert(node, adj);
}
adjacency.sealed.fit();
}
fn build_shard(
rows: &[RelRow],
shard: &[usize],
side: Side,
sealed: &SealedArena,
) -> Vec<(NodeId, TypedAdj)> {
let endpoint = |row: &RelRow| side.endpoint(row);
let mut order = shard.to_vec();
order.sort_unstable_by(|&a, &b| {
let (a, b) = (&rows[a], &rows[b]);
endpoint(a)
.cmp(&endpoint(b))
.then(a.type_id.cmp(&b.type_id))
});
let mut built = Vec::new();
for node_run in order.chunk_by(|&a, &b| endpoint(&rows[a]) == endpoint(&rows[b])) {
built.push(build_node(rows, node_run, side, sealed));
}
built
}
fn build_node(
rows: &[RelRow],
node_run: &[usize],
side: Side,
sealed: &SealedArena,
) -> (NodeId, TypedAdj) {
let node = side.endpoint(&rows[node_run[0]]);
let runs = node_run
.chunk_by(|&a, &b| rows[a].type_id == rows[b].type_id)
.map(|run| {
let hops: Vec<Hop> = run
.iter()
.map(|&index| {
let row = &rows[index];
Hop {
ts: row.ts,
id: row.id,
}
})
.collect();
(rows[run[0]].type_id, hops)
});
let mut adj = TypedAdj::from_runs(runs);
let gate = FoldGate::BuildSeal;
let due = gate.due(&adj, None, 0);
adj.fold_due(sealed.region_or_default(node), &due, 0, gate.floor());
(node, adj)
}
pub(super) fn adj_build(graph: &Graph, rows: &[RelRow], start_shards: &[Vec<usize>]) {
build_side(graph, rows, Side::Start, start_shards);
let end_shards = shard::shard_rows(rows, |row| row.end);
build_side(graph, rows, Side::End, &end_shards);
}
impl Graph {
pub(super) fn compact_adjacency_at_watermark(&self, horizon: u64) {
self.fold_adjacency_at_watermark(horizon);
self.sealed_out.compact();
self.sealed_in.compact();
}
pub(super) fn fold_adjacency_at_watermark(&self, horizon: u64) {
self.out_side().fold(horizon, FoldGate::Watermark);
self.in_side().fold(horizon, FoldGate::Watermark);
}
#[cfg(feature = "test-hooks")]
pub fn sealed_chunk_count(&self, node: NodeId, side: Side) -> usize {
let sealed = match side {
Side::Start => &self.sealed_out,
Side::End => &self.sealed_in,
};
sealed.region(node).map_or(0, |region| region.chunk_count())
}
pub fn degree_out(&self, id: NodeId) -> Vec<RelId> {
self.out_side().flatten(id)
}
pub(crate) fn typed_adj_len(
&self,
id: NodeId,
dir: relate_ir::Direction,
types: &RelTypes,
) -> usize {
let Some(ids) = types.ids() else {
return self.adj_len(id, dir);
};
self.sides(dir)
.map(|(side, _)| side.typed_len(id, ids.clone()))
.sum()
}
pub(crate) fn out_chunk_len(&self, node: NodeId, type_id: u32) -> u64 {
self.out_side().typed_len(node, std::iter::once(type_id)) as u64
}
pub(super) fn out_chunks(&self, node: NodeId) -> Vec<(u32, u64)> {
self.out_side()
.hop_counts(node)
.into_iter()
.map(|c| (c.type_id, c.hops as u64))
.collect()
}
pub fn adj_len(&self, id: NodeId, dir: relate_ir::Direction) -> usize {
self.sides(dir).map(|(side, _)| side.len(id)).sum()
}
pub fn degree_in(&self, id: NodeId) -> Vec<RelId> {
self.in_side().flatten(id)
}
pub fn neighbors(&self, id: NodeId, dir: relate_ir::Direction) -> Vec<RelId> {
self.neighbors_at(id, dir, self.read_ts())
}
pub fn for_each_neighbor_at<T: AsRef<str>>(
&self,
id: NodeId,
dir: relate_ir::Direction,
ts: u64,
types: &[T],
mut f: impl FnMut(RelId),
) {
let types = self.rel_types(types);
self.try_for_each_neighbor_resolved_at(id, dir, ts, &types, |rid| {
f(rid);
Ok::<(), std::convert::Infallible>(())
})
.expect("the closure is infallible");
}
pub(crate) fn try_for_each_neighbor_resolved_at<E>(
&self,
id: NodeId,
dir: relate_ir::Direction,
ts: u64,
types: &RelTypes,
mut f: impl FnMut(RelId) -> std::result::Result<(), E>,
) -> std::result::Result<(), E> {
self.try_for_each_hop_resolved_at(id, dir, ts, types, |rid, _| f(rid))
}
pub(crate) fn try_for_each_hop_resolved_at<E>(
&self,
id: NodeId,
dir: relate_ir::Direction,
ts: u64,
types: &RelTypes,
mut f: impl FnMut(RelId, NodeId) -> std::result::Result<(), E>,
) -> std::result::Result<(), E> {
use relate_ir::Direction;
let mut emit = |rid: RelId, start: NodeId, end: NodeId| {
match crate::store::hop_other(id, start, end, dir) {
Some(peer) => f(rid, peer),
None => Ok(()),
}
};
match dir {
Direction::Outgoing => {
self.for_each_typed_ends(self.out_side(), id, ts, types, &mut emit)?;
}
Direction::Incoming => {
self.for_each_typed_ends(self.in_side(), id, ts, types, &mut emit)?;
}
Direction::Both => {
let mut seen = crate::UsedSet::default();
let mut dedup = |rid: RelId, start: NodeId, end: NodeId| {
if seen.insert(rid) {
emit(rid, start, end)?;
}
Ok(())
};
self.for_each_typed_ends(self.out_side(), id, ts, types, &mut dedup)?;
self.for_each_typed_ends(self.in_side(), id, ts, types, &mut dedup)?;
}
}
Ok(())
}
fn for_each_typed_ends<E>(
&self,
side: AdjSide<'_>,
id: NodeId,
ts: u64,
types: &RelTypes,
f: &mut impl FnMut(RelId, NodeId, NodeId) -> std::result::Result<(), E>,
) -> std::result::Result<(), E> {
let hops = side
.with_adj(id, |by_type, region| {
let mut hops = Vec::new();
match types.ids() {
None => by_type.for_each_hop(region, ts, |hop| hops.push(hop.id)),
Some(ids) => {
for tid in ids {
by_type.for_each_hop_of(region, tid, ts, |hop| hops.push(hop.id));
}
}
}
hops
})
.unwrap_or_default();
for rid in hops {
if let Some((start, end)) = self.rel_ends_at(rid, ts) {
f(rid, start, end)?;
}
}
Ok(())
}
pub fn neighbors_at(&self, id: NodeId, dir: relate_ir::Direction, ts: u64) -> Vec<RelId> {
let mut out = Vec::new();
self.for_each_neighbor_at(id, dir, ts, &[] as &[String], |rid| out.push(rid));
out
}
}