Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-graph/src/split.rs

//! A graph cut into parts by a declared key, for local-first rounds over parts.
//!
//! The key is the graph's own ([`SplitKey`]): a node property (the crate of a code graph, a
//! region), blocks of ids (a set's vertex types in its id space, or regions as id blocks),
//! or a hash of the id when nothing better is known. The cut is made here, when the graph
//! is loaded; nothing is written back to the source.
//!
//! Each [`Part`] holds the sub-matrix of its internal edges in its own local ids and its
//! [`Border`]: the edges that leave the part, each with the target's part and id. The ids
//! of a split are one id space ([`SplitIds`]): part `p` holds ids `base(p)..base(p) +
//! count(p)`, its local id `l` is id `base(p) + l`, so the part of an id is answered from
//! the numbers alone. A key of id blocks keeps every node's id; another key numbers each
//! part's nodes in rising original id, and [`SplitIds`] maps both ways.

use std::ops::Range;

use kleene_sparse::{Csr, Semiring, Value};

use crate::graph::GraphError;

/// How a graph is cut into parts.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum SplitKey {
    /// Per node its key's value (a crate, a region), `values[v]` for node `v`: the nodes of
    /// one value form one part, parts in rising value. Values no node has make no part.
    Property(Vec<u32>),
    /// Parts as blocks of ids: block `k` starts at `starts[k]` (rising, the first 0) and
    /// ends where the next starts (the last at the node count). A set's vertex types in its
    /// id space (their bases), or regions as blocks of ids. Ids are kept as they are.
    Blocks(Vec<u64>),
    /// This many parts by a hash of the node id: the fallback when no key is declared.
    Hash(u32),
}

/// The ids of a split: per part a base and a count, and the map to the original ids.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SplitIds {
    /// `bases[p]` is part `p`'s first id; one more entry, the id count.
    bases: Vec<u64>,
    /// Original id -> split id; `None`: the same.
    to_split: Option<Vec<u32>>,
    /// Split id -> original id; `None`: the same.
    to_original: Option<Vec<u32>>,
}

impl SplitIds {
    /// The ids `key` gives a graph of `n` nodes, made from the node count and the key alone
    /// (no edge read): the ids [`Split::new`] and [`Split::part_only`] give the same graph,
    /// for a coordinator that places sources but holds no part.
    pub fn of(n: usize, key: &SplitKey) -> crate::Result<Self> {
        Ok(assign(n, key)?.0)
    }

    /// The number of parts.
    pub fn parts(&self) -> usize {
        self.bases.len() - 1
    }

    /// The number of ids (every part's nodes).
    pub fn total(&self) -> u64 {
        *self.bases.last().expect("one base past the parts")
    }

    /// Part `p`'s first id.
    pub fn base(&self, p: u32) -> u64 {
        self.bases[p as usize]
    }

    /// Part `p`'s node count.
    pub fn count(&self, p: u32) -> u64 {
        self.bases[p as usize + 1] - self.bases[p as usize]
    }

    /// Part `p`'s ids.
    pub fn range(&self, p: u32) -> Range<u64> {
        self.bases[p as usize]..self.bases[p as usize + 1]
    }

    /// `(base, count)` of every part, in part order.
    pub fn blocks(&self) -> impl Iterator<Item = (u64, u64)> + '_ {
        self.bases.windows(2).map(|w| (w[0], w[1] - w[0]))
    }

    /// The part holding id `id`, from the bases alone.
    pub fn part_of(&self, id: u64) -> Option<u32> {
        if id >= self.total() {
            return None;
        }
        // The last part whose base is at or below `id` (empty parts share their base with
        // the next one and are passed over).
        let p = self.bases.partition_point(|&b| b <= id) - 1;
        Some(p as u32)
    }

    /// The part and local id of id `id`.
    pub fn locate(&self, id: u64) -> Option<(u32, u32)> {
        let p = self.part_of(id)?;
        Some((p, (id - self.base(p)) as u32))
    }

    /// The id of part `p`'s local node `local`.
    pub fn id(&self, p: u32, local: u32) -> Option<u64> {
        let r = self.range(p);
        let id = r.start + local as u64;
        (id < r.end).then_some(id)
    }

    /// The split id of original node `v`.
    pub fn from_original(&self, v: u32) -> Option<u64> {
        match &self.to_split {
            Some(m) => m.get(v as usize).map(|&x| x as u64),
            None => (u64::from(v) < self.total()).then_some(v as u64),
        }
    }

    /// The original node of split id `id`.
    pub fn original(&self, id: u64) -> Option<u32> {
        match &self.to_original {
            Some(m) => m.get(id as usize).copied(),
            None => (id < self.total()).then_some(id as u32),
        }
    }

    /// Whether split ids are the original ids (a key of id blocks).
    pub fn is_identity(&self) -> bool {
        self.to_split.is_none()
    }
}

/// The edges that leave a part, by local source: each with the target's split id and part.
#[derive(Clone, Debug, PartialEq)]
pub struct Border<T: Value> {
    offsets: Vec<u64>,
    to: Vec<u64>,
    part: Vec<u32>,
    values: Option<Vec<T>>,
}

impl<T: Value> Border<T> {
    /// The number of border edges.
    pub fn len(&self) -> usize {
        self.to.len()
    }

    /// Whether the part has no edge out.
    pub fn is_empty(&self) -> bool {
        self.to.is_empty()
    }

    /// The places of local node `local`'s border edges.
    pub fn range(&self, local: u32) -> Range<usize> {
        if self.offsets.is_empty() {
            return 0..0;
        }
        self.offsets[local as usize] as usize..self.offsets[local as usize + 1] as usize
    }

    /// The target split id of every border edge, by local source.
    pub fn targets(&self) -> &[u64] {
        &self.to
    }

    /// The target part of every border edge, by local source.
    pub fn target_parts(&self) -> &[u32] {
        &self.part
    }

    /// The values of the border edges, `None` when structural.
    pub fn values(&self) -> Option<&[T]> {
        self.values.as_deref()
    }

    /// The `u64` offsets: local node `l`'s edges are places `offsets[l]..offsets[l + 1]`
    /// (empty for a part with no border: [`Split::whole`] allocates nothing per node).
    pub fn offsets(&self) -> &[u64] {
        &self.offsets
    }
}

/// One part of a split: its internal edges as a matrix in local ids, and its border.
#[derive(Clone, Debug)]
pub struct Part<T: Value> {
    index: u32,
    base: u64,
    inner: Csr<T>,
    border: Border<T>,
}

impl<T: Value> Part<T> {
    /// The part's number.
    pub fn index(&self) -> u32 {
        self.index
    }

    /// The split id of its local node 0.
    pub fn base(&self) -> u64 {
        self.base
    }

    /// Its node count.
    pub fn count(&self) -> usize {
        self.inner.nrows()
    }

    /// Its internal edges: `count` by `count`, in local ids.
    pub fn inner(&self) -> &Csr<T> {
        &self.inner
    }

    /// Its edges out.
    pub fn border(&self) -> &Border<T> {
        &self.border
    }

    /// The small summary a part sends the coordinator: its ids, its edge counts, and per
    /// neighbouring part the number of border edges leading there.
    pub fn summary(&self) -> PartSummary {
        let mut to: Vec<(u32, u64)> = Vec::new();
        let mut counts = std::collections::BTreeMap::new();
        for &q in &self.border.part {
            *counts.entry(q).or_insert(0u64) += 1;
        }
        to.extend(counts);
        PartSummary {
            part: self.index,
            base: self.base,
            count: self.count() as u64,
            inner_edges: self.inner.nnz() as u64,
            border: to,
        }
    }

    /// The border edges of local nodes `locals`: `(target split id, target part)` of each,
    /// each target once, ids rising.
    pub fn border_targets(&self, locals: &[u32]) -> Vec<(u64, u32)> {
        let b = &self.border;
        let mut out: Vec<(u64, u32)> = locals
            .iter()
            .flat_map(|&l| b.range(l).map(|k| (b.to[k], b.part[k])))
            .collect();
        out.sort_unstable();
        out.dedup();
        out
    }

    /// The part with its matrix and border structural in another value type (each entry
    /// the semiring's one): no buffer copied but the border's.
    pub fn structural<U: Value>(&self) -> Part<U> {
        Part {
            index: self.index,
            base: self.base,
            inner: self.inner.pattern().to_structural::<U>(),
            border: Border {
                offsets: self.border.offsets.clone(),
                to: self.border.to.clone(),
                part: self.border.part.clone(),
                values: None,
            },
        }
    }
}

/// What a part tells the coordinator about itself.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PartSummary {
    /// The part's number.
    pub part: u32,
    /// Its first split id.
    pub base: u64,
    /// Its node count.
    pub count: u64,
    /// Its internal edges.
    pub inner_edges: u64,
    /// Per part its border leads to (rising), the number of border edges.
    pub border: Vec<(u32, u64)>,
}

/// A graph cut into parts ([`SplitKey`]), in one id space ([`SplitIds`]).
#[derive(Clone, Debug)]
pub struct Split<T: Value> {
    ids: SplitIds,
    parts: Vec<Part<T>>,
}

impl<T: Value> Split<T> {
    /// The split of the graph of `n` nodes with edges `src[k] -> dst[k]` (values
    /// `values[k]`, or structural) by `key`. A repeated edge is kept once, its values
    /// folded with `s`'s add (as [`Csr::from_edges`] does).
    pub fn new<S: Semiring<T = T>>(
        n: usize,
        src: &[u32],
        dst: &[u32],
        values: Option<&[T]>,
        key: &SplitKey,
        s: S,
    ) -> crate::Result<Self> {
        if src.len() != dst.len() || values.is_some_and(|v| v.len() != src.len()) {
            return Err(GraphError::Split(format!(
                "edge lists of {} sources, {} targets and {} values",
                src.len(),
                dst.len(),
                values.map_or(src.len(), |v| v.len())
            )));
        }
        if let Some(&v) = src.iter().chain(dst).find(|&&v| v as usize >= n) {
            return Err(GraphError::SourceOutOfRange {
                source: v,
                vertices: n,
            });
        }
        let (ids, blocks) = assign(n, key)?;
        let part_of = blocks.unwrap_or_else(|| block_parts(&ids));
        let nparts = ids.parts();
        let local = |v: u32| -> u32 {
            (ids.from_original(v).expect("a node of the split") - ids.base(part_of[v as usize]))
                as u32
        };
        // Per part: inner edges in local ids, border edges by local source.
        let mut inner: Vec<Edges<T>> = (0..nparts).map(|_| Default::default()).collect();
        let mut out: Vec<Vec<(u32, u64, u32, T)>> = vec![Vec::new(); nparts];
        for k in 0..src.len() {
            let (u, v) = (src[k], dst[k]);
            let (pu, pv) = (part_of[u as usize], part_of[v as usize]);
            let w = values.map_or(s.one(), |x| x[k]);
            if pu == pv {
                inner[pu as usize].push(local(u), local(v), w, values.is_some());
            } else {
                let id = ids.from_original(v).expect("a node of the split");
                out[pu as usize].push((local(u), id, pv, w));
            }
        }
        let mut parts = Vec::with_capacity(nparts);
        for (p, (e, b)) in inner.into_iter().zip(out).enumerate() {
            parts.push(build_part(p as u32, &ids, e, b, values.is_some(), s)?);
        }
        Ok(Split { ids, parts })
    }

    /// The graph of matrix `a` as one part: the matrix shared as it is (no copy), no
    /// border, ids the matrix's own. The same as [`Split::new`] with [`SplitKey::Blocks`]
    /// `[0]`: a graph on one machine is a split of one part.
    pub fn whole(a: Csr<T>) -> crate::Result<Self> {
        if a.nrows() != a.ncols() {
            return Err(GraphError::NotSquare {
                rows: a.nrows(),
                cols: a.ncols(),
            });
        }
        let n = a.nrows();
        Ok(Split {
            ids: SplitIds {
                bases: vec![0, n as u64],
                to_split: None,
                to_original: None,
            },
            parts: vec![Part {
                index: 0,
                base: 0,
                inner: a,
                border: Border {
                    offsets: Vec::new(),
                    to: Vec::new(),
                    part: Vec::new(),
                    values: None,
                },
            }],
        })
    }

    /// The split of the matrix `a`'s graph (rows are sources) by `key`.
    pub fn from_csr<S: Semiring<T = T>>(a: &Csr<T>, key: &SplitKey, s: S) -> crate::Result<Self> {
        if a.nrows() != a.ncols() {
            return Err(GraphError::NotSquare {
                rows: a.nrows(),
                cols: a.ncols(),
            });
        }
        let mut src = Vec::with_capacity(a.nnz());
        for i in 0..a.nrows() {
            src.extend(std::iter::repeat_n(i as u32, a.row(i).len()));
        }
        let values = a.values().map(|v| v.to_vec());
        Self::new(
            a.nrows(),
            &src,
            a.pattern().indices(),
            values.as_deref(),
            key,
            s,
        )
    }

    /// Part `p` alone of the split of matrix `a`'s graph by `key`, with the split's ids: the
    /// part and its summary are the ones [`Split::new`] gives, and only the rows of the
    /// part's own nodes are read (`a`'s rows are its sources). Where `a` maps its files
    /// (a GraphAr edge table of one chunk, [`Csr::with_pattern`] over mapped buffers), only
    /// the pages of those rows are read: a key of id blocks reads one run of rows, a
    /// property or hash key the part's rows wherever they lie. What every machine keeps
    /// besides its part: the ids, one base per part for a key of id blocks, two maps of 4
    /// bytes a node for another key (a border target's part and id need them).
    pub fn part_only<S: Semiring<T = T>>(
        a: &Csr<T>,
        key: &SplitKey,
        p: u32,
        s: S,
    ) -> crate::Result<(SplitIds, Part<T>)> {
        if a.nrows() != a.ncols() {
            return Err(GraphError::NotSquare {
                rows: a.nrows(),
                cols: a.ncols(),
            });
        }
        let (ids, part_of) = assign(a.nrows(), key)?;
        if p as usize >= ids.parts() {
            return Err(GraphError::Split(format!(
                "no part {p} in a split of {}",
                ids.parts()
            )));
        }
        let part = |v: u32| -> (u32, u64) {
            let id = ids.from_original(v).expect("a node of the split");
            let q = match &part_of {
                Some(m) => m[v as usize],
                None => ids.part_of(id).expect("an id of the split"),
            };
            (q, id)
        };
        let base = ids.base(p);
        let values = a.values();
        let (mut inner, mut out) = (Edges::default(), Vec::new());
        for l in 0..ids.count(p) as u32 {
            let u = ids.original(base + l as u64).expect("an id of the split") as usize;
            let r = a.pattern().range(u);
            for k in r {
                let v = a.pattern().indices()[k];
                let w = values.map_or(s.one(), |x| x[k]);
                let (q, id) = part(v);
                if q == p {
                    inner.push(l, (id - base) as u32, w, values.is_some());
                } else {
                    out.push((l, id, q, w));
                }
            }
        }
        let part = build_part(p, &ids, inner, out, values.is_some(), s)?;
        Ok((ids, part))
    }

    /// Part `p` alone of the split by `key` of the graph of `n` nodes with edges `src[k] ->
    /// dst[k]`, for a source that cannot read a part's rows alone (rows by no order, as an
    /// Iceberg table's): every edge is read once and only the part's are kept. The part
    /// and its summary are [`Split::new`]'s; the cost is the whole scan, the memory the
    /// part's and the ids'.
    pub fn part_of_edges<S: Semiring<T = T>>(
        n: usize,
        src: &[u32],
        dst: &[u32],
        values: Option<&[T]>,
        key: &SplitKey,
        p: u32,
        s: S,
    ) -> crate::Result<(SplitIds, Part<T>)> {
        if src.len() != dst.len() || values.is_some_and(|v| v.len() != src.len()) {
            return Err(GraphError::Split(format!(
                "edge lists of {} sources, {} targets and {} values",
                src.len(),
                dst.len(),
                values.map_or(src.len(), |v| v.len())
            )));
        }
        if let Some(&v) = src.iter().chain(dst).find(|&&v| v as usize >= n) {
            return Err(GraphError::SourceOutOfRange {
                source: v,
                vertices: n,
            });
        }
        let (ids, part_of) = assign(n, key)?;
        if p as usize >= ids.parts() {
            return Err(GraphError::Split(format!(
                "no part {p} in a split of {}",
                ids.parts()
            )));
        }
        let part = |v: u32| -> (u32, u64) {
            let id = ids.from_original(v).expect("a node of the split");
            let q = match &part_of {
                Some(m) => m[v as usize],
                None => ids.part_of(id).expect("an id of the split"),
            };
            (q, id)
        };
        let base = ids.base(p);
        let (mut inner, mut out) = (Edges::default(), Vec::new());
        for k in 0..src.len() {
            let (pu, iu) = part(src[k]);
            if pu != p {
                continue;
            }
            let w = values.map_or(s.one(), |x| x[k]);
            let (pv, iv) = part(dst[k]);
            let l = (iu - base) as u32;
            if pv == p {
                inner.push(l, (iv - base) as u32, w, values.is_some());
            } else {
                out.push((l, iv, pv, w));
            }
        }
        let part = build_part(p, &ids, inner, out, values.is_some(), s)?;
        Ok((ids, part))
    }

    /// The split's ids.
    pub fn ids(&self) -> &SplitIds {
        &self.ids
    }

    /// The parts, in order.
    pub fn parts(&self) -> &[Part<T>] {
        &self.parts
    }

    /// Part `p`.
    pub fn part(&self, p: u32) -> &Part<T> {
        &self.parts[p as usize]
    }

    /// The ids and the parts, taken apart.
    pub fn into_parts(self) -> (SplitIds, Vec<Part<T>>) {
        (self.ids, self.parts)
    }

    /// Every part's summary.
    pub fn summaries(&self) -> Vec<PartSummary> {
        self.parts.iter().map(Part::summary).collect()
    }

    /// The edges of all parts, inner and border, as `(original source, original target,
    /// value)` (structural: the semiring's one): every edge of the graph once.
    pub fn edges<S: Semiring<T = T>>(&self, s: S) -> Vec<(u32, u32, T)> {
        let mut e = Vec::new();
        let orig = |id: u64| self.ids.original(id).expect("an id of the split");
        for p in &self.parts {
            for (l, t, w) in p.inner.triples(s) {
                e.push((orig(p.base + l as u64), orig(p.base + t as u64), w));
            }
            for l in 0..p.count() as u32 {
                for k in p.border.range(l) {
                    let w = p.border.values.as_ref().map_or(s.one(), |v| v[k]);
                    e.push((orig(p.base + l as u64), orig(p.border.to[k]), w));
                }
            }
        }
        e
    }

    /// The split with every part structural in another value type ([`Part::structural`]).
    pub fn structural<U: Value>(&self) -> Split<U> {
        Split {
            ids: self.ids.clone(),
            parts: self.parts.iter().map(Part::structural).collect(),
        }
    }
}

/// A part's inner edges in local ids, gathered before its matrix is built.
struct Edges<T> {
    src: Vec<u32>,
    dst: Vec<u32>,
    values: Vec<T>,
}

impl<T> Default for Edges<T> {
    fn default() -> Self {
        Edges {
            src: Vec::new(),
            dst: Vec::new(),
            values: Vec::new(),
        }
    }
}

impl<T> Edges<T> {
    fn push(&mut self, u: u32, v: u32, w: T, valued: bool) {
        self.src.push(u);
        self.dst.push(v);
        if valued {
            self.values.push(w);
        }
    }
}

/// Part `p` from its inner edges and its border edges `(local source, target id, target
/// part, value)`: the one builder of [`Split::new`], [`Split::part_only`] and
/// [`Split::part_of_edges`]. A repeated edge is kept once, its values folded.
fn build_part<T: Value, S: Semiring<T = T>>(
    p: u32,
    ids: &SplitIds,
    e: Edges<T>,
    mut b: Vec<(u32, u64, u32, T)>,
    valued: bool,
    s: S,
) -> crate::Result<Part<T>> {
    let count = ids.count(p) as usize;
    let m = Csr::from_edges(
        count,
        count,
        &e.src,
        &e.dst,
        valued.then_some(e.values.as_slice()),
        s,
    )?;
    b.sort_unstable_by_key(|e| (e.0, e.1));
    let mut offsets = vec![0u64; count + 1];
    let (mut to, mut tp, mut tv) = (Vec::new(), Vec::new(), Vec::new());
    let mut last: Option<(u32, u64)> = None;
    for (l, id, q, w) in b {
        if last == Some((l, id)) {
            // A repeated edge: kept once, its values folded.
            if valued {
                let k = tv.len() - 1;
                tv[k] = s.add(tv[k], w);
            }
            continue;
        }
        last = Some((l, id));
        to.push(id);
        tp.push(q);
        if valued {
            tv.push(w);
        }
        offsets[l as usize + 1] += 1;
    }
    for l in 0..count {
        offsets[l + 1] += offsets[l];
    }
    Ok(Part {
        index: p,
        base: ids.base(p),
        inner: m,
        border: Border {
            offsets,
            to,
            part: tp,
            values: valued.then_some(tv),
        },
    })
}

/// Each node's part for a key of id blocks (its ids are the nodes').
pub(crate) fn block_parts(ids: &SplitIds) -> Vec<u32> {
    let mut part_of = vec![0u32; ids.total() as usize];
    for (p, (b, c)) in ids.blocks().enumerate() {
        part_of[b as usize..(b + c) as usize].fill(p as u32);
    }
    part_of
}

/// Each original node's part (`None` for a key of id blocks: the ids answer it), and the
/// split's ids.
pub(crate) fn assign(n: usize, key: &SplitKey) -> crate::Result<(SplitIds, Option<Vec<u32>>)> {
    if n > u32::MAX as usize {
        return Err(GraphError::TooManyVertices {
            vertices: n,
            limit: u32::MAX as usize,
        });
    }
    match key {
        SplitKey::Blocks(starts) => {
            if starts.first() != Some(&0) || starts.windows(2).any(|w| w[0] > w[1]) {
                return Err(GraphError::Split(
                    "blocks must start at 0 and rise".to_string(),
                ));
            }
            if let Some(&s) = starts.iter().find(|&&s| s > n as u64) {
                return Err(GraphError::Split(format!(
                    "a block starts at {s}, past the {n} nodes"
                )));
            }
            let mut bases = starts.clone();
            bases.push(n as u64);
            Ok((
                SplitIds {
                    bases,
                    to_split: None,
                    to_original: None,
                },
                None,
            ))
        }
        SplitKey::Property(values) => {
            if values.len() != n {
                return Err(GraphError::Split(format!(
                    "a key value for {} nodes, the graph has {n}",
                    values.len()
                )));
            }
            let mut distinct: Vec<u32> = values.clone();
            distinct.sort_unstable();
            distinct.dedup();
            let part_of = values
                .iter()
                .map(|v| distinct.binary_search(v).expect("a value seen") as u32)
                .collect();
            Ok(renumber(distinct.len(), part_of))
        }
        SplitKey::Hash(k) => {
            if *k == 0 {
                return Err(GraphError::Split("a hash into 0 parts".to_string()));
            }
            let part_of = (0..n as u64)
                .map(|v| ((v.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32) % *k as u64) as u32)
                .collect();
            Ok(renumber(*k as usize, part_of))
        }
    }
}

/// Ids numbering each part's nodes in rising original id, parts one after the other.
fn renumber(nparts: usize, part_of: Vec<u32>) -> (SplitIds, Option<Vec<u32>>) {
    let mut bases = vec![0u64; nparts + 1];
    for &p in &part_of {
        bases[p as usize + 1] += 1;
    }
    for p in 0..nparts {
        bases[p + 1] += bases[p];
    }
    let mut next = bases.clone();
    let mut to_split = vec![0u32; part_of.len()];
    let mut to_original = vec![0u32; part_of.len()];
    for (v, &p) in part_of.iter().enumerate() {
        let id = next[p as usize];
        next[p as usize] += 1;
        to_split[v] = id as u32;
        to_original[id as usize] = v as u32;
    }
    (
        SplitIds {
            bases,
            to_split: Some(to_split),
            to_original: Some(to_original),
        },
        Some(part_of),
    )
}