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

nordisk/kleene

crates/kleene-index/src/central.rs

//! The coordinator's small central index over a split graph: where each part lives, which
//! ids it holds, which parts its border leads to, and optionally the names.
//!
//! Built from the indexes that exist: the id ranges are a [`kleene_gar::IdSpace`] with one
//! row per part (a base and a count, the part of an id answered from the numbers), the part
//! graph is an ordinary small graph whose [`Reach`] answers "can part A reach part B",
//! the names are [`Names`] as they are, and [`Store`] keeps the tables. New here are only
//! the pass that builds the part graph from the parts' summaries and the placement table
//! (part -> machine). The coordinator never holds the graph. One machine is the same code
//! with one part: one id range, a part graph of one node, nothing to prune.

use kleene_gar::IdSpace;
use kleene_graph::{PartOrder, PartSummary};

use crate::error::{IndexError, Result};
use crate::names::Names;
use crate::reach::Reach;
use crate::store::{Store, col32, col64};

/// The index name [`Central::save`] stores under.
pub const CENTRAL: &str = "central";

/// The central index's tables as plain data, for a codec to send elsewhere (the names are
/// not in them; [`Names`] are kept as they are). [`Central::tables`] gives them,
/// [`Central::from_tables`] builds the index from them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CentralTables {
    /// Per part its node count (the id ranges follow, parts one after the other).
    pub counts: Vec<u64>,
    /// Per part the machine that holds it.
    pub placement: Vec<u32>,
    /// The part graph: part `p`'s neighbours are `to[off[p]..off[p + 1]]`.
    pub off: Vec<u64>,
    /// The part graph's neighbouring parts.
    pub to: Vec<u32>,
    /// The border edges to each neighbour, at the same places as `to`.
    pub edges: Vec<u64>,
}

impl CentralTables {
    /// The tables as bytes: five little-endian columns, each its length (u64) then its
    /// values.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut b = Vec::new();
        let u64s = |b: &mut Vec<u8>, v: &[u64]| {
            b.extend((v.len() as u64).to_le_bytes());
            for x in v {
                b.extend(x.to_le_bytes());
            }
        };
        let u32s = |b: &mut Vec<u8>, v: &[u32]| {
            b.extend((v.len() as u64).to_le_bytes());
            for x in v {
                b.extend(x.to_le_bytes());
            }
        };
        u64s(&mut b, &self.counts);
        u32s(&mut b, &self.placement);
        u64s(&mut b, &self.off);
        u32s(&mut b, &self.to);
        u64s(&mut b, &self.edges);
        b
    }

    /// The tables [`CentralTables::to_bytes`] wrote.
    pub fn from_bytes(b: &[u8]) -> Result<Self> {
        let mut r = Reader { b, at: 0 };
        let t = CentralTables {
            counts: r.u64s()?,
            placement: r.u32s()?,
            off: r.u64s()?,
            to: r.u32s()?,
            edges: r.u64s()?,
        };
        if r.at != b.len() {
            return Err(IndexError::Bad(format!(
                "central tables: {} bytes past the end",
                b.len() - r.at
            )));
        }
        Ok(t)
    }
}

/// Little-endian columns read off bytes.
struct Reader<'a> {
    b: &'a [u8],
    at: usize,
}

impl<'a> Reader<'a> {
    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
        let s = self
            .at
            .checked_add(n)
            .and_then(|e| self.b.get(self.at..e))
            .ok_or_else(|| IndexError::Bad("central tables cut short".to_string()))?;
        self.at += n;
        Ok(s)
    }

    fn len(&mut self, width: usize) -> Result<usize> {
        let s = self.take(8)?;
        let n = u64::from_le_bytes(s.try_into().expect("8 bytes"));
        usize::try_from(n)
            .ok()
            .and_then(|n| n.checked_mul(width))
            .ok_or_else(|| IndexError::Bad(format!("a column of {n} values is too long")))
    }

    fn u64s(&mut self) -> Result<Vec<u64>> {
        let n = self.len(8)?;
        let (words, _) = self.take(n)?.as_chunks::<8>();
        Ok(words.iter().map(|c| u64::from_le_bytes(*c)).collect())
    }

    fn u32s(&mut self) -> Result<Vec<u32>> {
        let n = self.len(4)?;
        let (words, _) = self.take(n)?.as_chunks::<4>();
        Ok(words.iter().map(|c| u32::from_le_bytes(*c)).collect())
    }
}

/// The coordinator's central index (see the module doc).
#[derive(Clone, Debug)]
pub struct Central {
    ids: IdSpace,
    placement: Vec<u32>,
    /// The part graph: per part its neighbouring parts (rising) with the border edges.
    off: Vec<u64>,
    to: Vec<u32>,
    edges: Vec<u64>,
    reach: Reach,
    names: Option<Names>,
}

fn part_name(p: usize) -> String {
    p.to_string()
}

impl Central {
    /// The index from every part's summary (in part order, as
    /// `kleene_graph::Split::summaries` gives them) and the placement: `placement[p]` is
    /// the machine that holds part `p`.
    pub fn build(summaries: &[PartSummary], placement: Vec<u32>) -> Result<Self> {
        if placement.len() != summaries.len() {
            return Err(IndexError::Bad(format!(
                "a placement of {} parts for {} parts",
                placement.len(),
                summaries.len()
            )));
        }
        let mut next = 0;
        for (p, s) in summaries.iter().enumerate() {
            if s.part as usize != p || s.base != next {
                return Err(IndexError::Bad(format!(
                    "part {} at base {} where part {p} at base {next} was due",
                    s.part, s.base
                )));
            }
            next += s.count;
        }
        let names: Vec<String> = (0..summaries.len()).map(part_name).collect();
        let ids = IdSpace::new(
            names
                .iter()
                .map(String::as_str)
                .zip(summaries.iter().map(|s| s.count)),
        );
        // The part graph: one pass over the summaries' border counts.
        let mut off = Vec::with_capacity(summaries.len() + 1);
        let (mut to, mut edges) = (Vec::new(), Vec::new());
        off.push(0);
        for s in summaries {
            for &(q, c) in &s.border {
                if q as usize >= summaries.len() {
                    return Err(IndexError::Bad(format!(
                        "part {} borders part {q}, past the {} parts",
                        s.part,
                        summaries.len()
                    )));
                }
                to.push(q);
                edges.push(c);
            }
            off.push(to.len() as u64);
        }
        Self::tables_in(ids, placement, off, to, edges)
    }

    /// Its tables as plain data (the names left out).
    pub fn tables(&self) -> CentralTables {
        CentralTables {
            counts: self.ids.types().map(|t| t.2).collect(),
            placement: self.placement.clone(),
            off: self.off.clone(),
            to: self.to.clone(),
            edges: self.edges.clone(),
        }
    }

    /// The index from its tables ([`Central::tables`]; no names).
    pub fn from_tables(t: CentralTables) -> Result<Self> {
        if t.placement.len() != t.counts.len() || t.off.len() != t.counts.len() + 1 {
            return Err(IndexError::Bad(format!(
                "central tables of {} parts, {} placements, {} offsets",
                t.counts.len(),
                t.placement.len(),
                t.off.len()
            )));
        }
        if t.to.len() != t.edges.len() || t.off.last().copied() != Some(t.to.len() as u64) {
            return Err(IndexError::Bad(
                "central tables: a part graph out of step".to_string(),
            ));
        }
        let names: Vec<String> = (0..t.counts.len()).map(part_name).collect();
        let ids = IdSpace::new(
            names
                .iter()
                .map(String::as_str)
                .zip(t.counts.iter().copied()),
        );
        Self::tables_in(ids, t.placement, t.off, t.to, t.edges)
    }

    fn tables_in(
        ids: IdSpace,
        placement: Vec<u32>,
        off: Vec<u64>,
        to: Vec<u32>,
        edges: Vec<u64>,
    ) -> Result<Self> {
        let reach = Reach::build(&off, &to)?;
        Ok(Central {
            ids,
            placement,
            off,
            to,
            edges,
            reach,
            names: None,
        })
    }

    /// With `names` (name -> node id, ids in the split's id space).
    pub fn with_names(mut self, names: Names) -> Self {
        self.names = Some(names);
        self
    }

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

    /// The id ranges: one row per part, named by its number.
    pub fn ids(&self) -> &IdSpace {
        &self.ids
    }

    /// The part holding id `id`, from the numbers alone.
    pub fn part_of(&self, id: u64) -> Option<u32> {
        self.ids.position(id).map(|(p, _)| p as u32)
    }

    /// The machine holding id `id`.
    pub fn machine_of(&self, id: u64) -> Option<u32> {
        self.part_of(id).map(|p| self.placement[p as usize])
    }

    /// The machine holding part `p`.
    pub fn machine(&self, p: u32) -> u32 {
        self.placement[p as usize]
    }

    /// The node named `name`, when the index has names.
    pub fn node(&self, name: &str) -> Option<u64> {
        self.names.as_ref()?.id(name).map(u64::from)
    }

    /// The parts part `p`'s border leads to, rising, with their border edge counts.
    pub fn borders(&self, p: u32) -> impl Iterator<Item = (u32, u64)> + '_ {
        let r = self.off[p as usize] as usize..self.off[p as usize + 1] as usize;
        self.to[r.clone()]
            .iter()
            .copied()
            .zip(self.edges[r].iter().copied())
    }

    /// The sweep order of the parts ([`PartOrder`]): the strong components of the part
    /// graph, feeders first, in levels. A part outside a circle runs once, after its
    /// feeders (`kleene_graph::reach_sweep`).
    pub fn order(&self) -> Result<PartOrder> {
        Ok(PartOrder::new(self.parts(), &self.off, &self.to)?)
    }

    /// The part graph's [`Reach`] ("can part A reach part B").
    pub fn part_reach(&self) -> &Reach {
        &self.reach
    }

    /// Pruning: the parts a search that starts in parts `starts` can ever reach (the starts
    /// included), rising. Only these are woken.
    pub fn wake(&self, starts: &[u32]) -> Vec<u32> {
        (0..self.parts() as u32)
            .filter(|&q| starts.iter().any(|&s| self.reach.reaches(s, q)))
            .collect()
    }

    /// The parts a search from node ids `starts` can reach, rising.
    pub fn wake_from(&self, starts: &[u64]) -> Result<Vec<u32>> {
        let parts = starts
            .iter()
            .map(|&s| {
                self.part_of(s)
                    .ok_or_else(|| IndexError::Bad(format!("node {s} past the id ranges")))
            })
            .collect::<Result<Vec<u32>>>()?;
        Ok(self.wake(&parts))
    }

    /// The machines to wake for a search from node ids `starts`, rising.
    pub fn machines_from(&self, starts: &[u64]) -> Result<Vec<u32>> {
        let mut m: Vec<u32> = self
            .wake_from(starts)?
            .into_iter()
            .map(|p| self.placement[p as usize])
            .collect();
        m.sort_unstable();
        m.dedup();
        Ok(m)
    }

    /// Keep the tables (counts, placement, part graph) in `store` under [`CENTRAL`]; the
    /// names are kept by their own index.
    pub fn save(&self, store: &Store) -> Result<()> {
        let counts: Vec<u64> = self.ids.types().map(|t| t.2).collect();
        store.save(
            CENTRAL,
            vec![
                ("counts", col64(counts)),
                ("placement", col32(self.placement.clone())),
                ("off", col64(self.off.clone())),
                ("to", col32(self.to.clone())),
                ("edges", col64(self.edges.clone())),
            ],
        )
    }

    /// The tables [`Central::save`] kept, if `store` has them.
    pub fn load(store: &Store) -> Result<Option<Self>> {
        let Some(s) = store.load(CENTRAL)? else {
            return Ok(None);
        };
        let counts = s.u64("counts")?;
        let names: Vec<String> = (0..counts.len()).map(part_name).collect();
        let ids = IdSpace::new(names.iter().map(String::as_str).zip(counts.iter().copied()));
        Self::tables_in(
            ids,
            s.u32("placement")?.to_vec(),
            s.u64("off")?.to_vec(),
            s.u32("to")?.to_vec(),
            s.u64("edges")?.to_vec(),
        )
        .map(Some)
    }
}