crates/kleene-index/src/computed.rs
//! A computed split ([`kleene_graph::computed_split`]) kept beside its set: computed once on
//! one machine (CPU or GPU), then read by every executor and the client.
//!
//! It is one index of the set's [`Store`] (the same directory, keyed by the set's root hash
//! or by [`Store::keyed`]), named `split.<edge>.k<parts>`: the part of every node as one
//! byte (`UInt8`, while K is at most 256), the nodes per part, the capacities when given,
//! and one `u64` row of what it was made from and found (snapshot, nodes, parts, rounds
//! asked, slack, seed, rounds run, crossing edges). The snapshot is written in the file and
//! checked on load: a file for another snapshot or another node count is refused, never
//! read as this one's.
use std::sync::Arc;
use arrow_array::{Array, ArrayRef, UInt8Array};
use kleene_graph::{ComputedSplit, SplitCompute};
use crate::error::{Result, bad};
use crate::store::{Store, col64};
/// The index name of the split of `edge` into `parts` parts.
fn name(edge: &str, parts: u32) -> Result<String> {
if edge.is_empty()
|| !edge
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
return Err(bad(format!(
"an edge label {edge:?} for a kept split (letters, digits, _ and - only)"
)));
}
Ok(format!("split.{edge}.k{parts}"))
}
/// Keep `split`, made by `how` over edge type `edge` of the set at `snapshot`, in `store`
/// (one per edge type and part count; a later save replaces it). Without a directory
/// ([`Store::memory`]) nothing is kept.
pub fn save_computed_split(
store: &Store,
edge: &str,
snapshot: u64,
how: &SplitCompute,
split: &ComputedSplit,
) -> Result<()> {
let k = how.parts;
if k == 0 || k > 256 || split.sizes.len() != k as usize {
return Err(bad(format!(
"a kept split of {} part sizes for {k} parts (1 to 256)",
split.sizes.len()
)));
}
if let Some(&p) = split.part.iter().find(|&&p| p >= k) {
return Err(bad(format!("a kept split with a node in part {p} of {k}")));
}
let name = name(edge, k)?;
let part: ArrayRef = Arc::new(UInt8Array::from_iter_values(
split.part.iter().map(|&p| p as u8),
));
let meta = vec![
snapshot,
split.part.len() as u64,
k as u64,
how.max_rounds as u64,
how.slack_permille as u64,
how.seed,
split.rounds as u64,
split.crossing_edges,
];
let mut cols = vec![
("part", part),
("sizes", col64(split.sizes.clone())),
("meta", col64(meta)),
];
if let Some(c) = &how.capacity {
cols.push(("capacity", col64(c.clone())));
}
store.save(&name, cols)
}
/// The split [`save_computed_split`] kept for edge type `edge` in `parts` parts, with the
/// [`SplitCompute`] it was made by; `None` when none is kept. A kept split for another
/// snapshot than `snapshot`, or another node count than `nodes`, is an error.
pub fn load_computed_split(
store: &Store,
edge: &str,
snapshot: u64,
parts: u32,
nodes: usize,
) -> Result<Option<(SplitCompute, ComputedSplit)>> {
let name = name(edge, parts)?;
let Some(s) = store.load(&name)? else {
return Ok(None);
};
let meta = s.u64("meta")?;
let &[snap, n, k, max_rounds, slack, seed, rounds, crossing] = &meta[..] else {
return Err(bad(format!("{name}: a meta row of {} numbers", meta.len())));
};
if snap != snapshot {
return Err(bad(format!(
"{name} was computed at snapshot {snap}, not {snapshot}"
)));
}
if n != nodes as u64 {
return Err(bad(format!(
"{name} was computed for {n} nodes, the graph has {nodes}"
)));
}
if k != parts as u64 {
return Err(bad(format!("{name} holds {k} parts, not {parts}")));
}
let array = s.array("part")?;
let bytes = array
.as_any()
.downcast_ref::<UInt8Array>()
.ok_or_else(|| bad(format!("{name}: parts not one byte a node")))?;
if bytes.len() != nodes || bytes.null_count() != 0 {
return Err(bad(format!(
"{name}: {} parts for {nodes} nodes",
bytes.len()
)));
}
let part: Vec<u32> = bytes.values().iter().map(|&p| p as u32).collect();
if let Some(&p) = part.iter().find(|&&p| p >= parts) {
return Err(bad(format!("{name}: a node in part {p} of {parts}")));
}
let sizes = s.u64("sizes")?.to_vec();
let mut count = vec![0u64; parts as usize];
for &p in &part {
count[p as usize] += 1;
}
if sizes != count {
return Err(bad(format!(
"{name}: part sizes that do not match its parts"
)));
}
let capacity = if s.has("capacity") {
Some(s.u64("capacity")?.to_vec())
} else {
None
};
let small = |x: u64, what: &str| {
u32::try_from(x).map_err(|_| bad(format!("{name}: {what} {x} past u32")))
};
let how = SplitCompute {
parts,
capacity,
max_rounds: small(max_rounds, "rounds asked")?,
slack_permille: small(slack, "slack")?,
seed,
};
let split = ComputedSplit {
part,
sizes,
crossing_edges: crossing,
rounds: small(rounds, "rounds")?,
};
Ok(Some((how, split)))
}