use crate::{
collections::Set,
error::CgkaError,
operation::{CgkaOperation, CgkaOperationGraph},
};
use alloc::{
collections::{binary_heap::PeekMut, BTreeMap, BTreeSet, BinaryHeap},
vec::Vec,
};
use keyhive_codec::{
error::DecodeError,
traits::{decode_exact, Decode, Encode, StreamDecode},
};
use keyhive_crypto::digest::Digest;
#[derive(Debug, Clone, Default, Hash, PartialEq, Eq)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub struct Predecessors(BTreeSet<Digest<CgkaOperation>>);
impl Predecessors {
pub fn heads_of(graph: &CgkaOperationGraph) -> Self {
graph.cgka_op_heads.iter().copied().collect()
}
pub fn contains_heads_of(&self, graph: &CgkaOperationGraph) -> bool {
self.missing_heads(graph).next().is_none()
}
fn missing_heads<'a>(
&'a self,
graph: &'a CgkaOperationGraph,
) -> impl Iterator<Item = Digest<CgkaOperation>> + 'a {
graph
.cgka_op_heads
.iter()
.filter(|head| !self.0.contains(head))
.copied()
}
pub(crate) fn filter_in_causal_past(
&self,
targets: BTreeSet<Digest<CgkaOperation>>,
graph: &CgkaOperationGraph,
) -> Result<BTreeSet<Digest<CgkaOperation>>, CgkaError> {
let missing_heads: Vec<_> = self.missing_heads(graph).collect();
if missing_heads.is_empty() {
return Ok(targets);
}
let mut found = BTreeSet::new();
let mut pending = BTreeMap::new();
for target in targets {
if self.contains(&target) {
found.insert(target);
} else {
pending.insert(target, graph.depth(&target)?);
}
}
let mut past = PastSearch {
frontier: self.iter().copied().collect(),
queued: self.iter().copied().collect(),
};
let mut concurrent = ConcurrentSearch::new(graph, missing_heads)?;
while let Some(min_pending_depth) = pending.values().copied().min() {
let Some(current) = past.next() else {
break;
};
if pending.remove(¤t).is_some() {
found.insert(current);
}
for pred in graph
.predecessors_for(¤t)
.ok_or(CgkaError::OperationNotFound)?
{
if graph.depth(pred)? >= min_pending_depth {
past.push(*pred);
}
}
match concurrent.next(graph, self, min_pending_depth)? {
None => {
found.extend(pending.into_keys());
break;
}
Some((current, in_past)) => {
if pending.remove(¤t).is_some() && in_past {
found.insert(current);
}
}
}
}
Ok(found)
}
pub fn iter(&self) -> impl Iterator<Item = &Digest<CgkaOperation>> {
self.0.iter()
}
pub fn contains(&self, op_hash: &Digest<CgkaOperation>) -> bool {
self.0.contains(op_hash)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl FromIterator<Digest<CgkaOperation>> for Predecessors {
fn from_iter<I: IntoIterator<Item = Digest<CgkaOperation>>>(iter: I) -> Self {
Self(iter.into_iter().collect())
}
}
impl<const N: usize> From<[Digest<CgkaOperation>; N]> for Predecessors {
fn from(op_hashes: [Digest<CgkaOperation>; N]) -> Self {
op_hashes.into_iter().collect()
}
}
impl<'a> IntoIterator for &'a Predecessors {
type Item = &'a Digest<CgkaOperation>;
type IntoIter = alloc::collections::btree_set::Iter<'a, Digest<CgkaOperation>>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl Encode for Predecessors {
fn encode_into(&self, out: &mut Vec<u8>) {
self.0.encode_into(out);
}
}
impl Decode for Predecessors {
fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
decode_exact(bytes)
}
}
impl StreamDecode for Predecessors {
fn decode_next(bytes: &[u8]) -> Result<(Self, &[u8]), DecodeError> {
let (op_hashes, rest) = BTreeSet::decode_next(bytes)?;
Ok((Self(op_hashes), rest))
}
}
struct PastSearch {
frontier: Vec<Digest<CgkaOperation>>,
queued: Set<Digest<CgkaOperation>>,
}
impl PastSearch {
fn push(&mut self, op_hash: Digest<CgkaOperation>) {
if self.queued.insert(op_hash) {
self.frontier.push(op_hash);
}
}
fn next(&mut self) -> Option<Digest<CgkaOperation>> {
self.frontier.pop()
}
}
struct ConcurrentSearch {
frontier: BinaryHeap<(u64, Digest<CgkaOperation>)>,
queued: Set<Digest<CgkaOperation>>,
outside: Set<Digest<CgkaOperation>>,
}
impl ConcurrentSearch {
fn new(
graph: &CgkaOperationGraph,
concurrent_heads: impl IntoIterator<Item = Digest<CgkaOperation>>,
) -> Result<Self, CgkaError> {
let mut search = Self {
frontier: BinaryHeap::new(),
queued: Set::new(),
outside: Set::new(),
};
for head in concurrent_heads {
search.push(graph, head)?;
}
Ok(search)
}
fn push(
&mut self,
graph: &CgkaOperationGraph,
op_hash: Digest<CgkaOperation>,
) -> Result<(), CgkaError> {
if self.queued.insert(op_hash) {
self.frontier.push((graph.depth(&op_hash)?, op_hash));
}
Ok(())
}
fn next(
&mut self,
graph: &CgkaOperationGraph,
predecessors: &Predecessors,
min_depth: u64,
) -> Result<Option<(Digest<CgkaOperation>, bool)>, CgkaError> {
let Some(deepest) = self
.frontier
.peek_mut()
.filter(|deepest| deepest.0 >= min_depth)
else {
return Ok(None);
};
let (_, current) = PeekMut::pop(deepest);
let in_past = predecessors.contains(¤t)
|| graph
.children_of(¤t)
.any(|child| !self.outside.contains(child));
if !in_past {
self.outside.insert(current);
for pred in graph
.predecessors_for(¤t)
.ok_or(CgkaError::OperationNotFound)?
{
self.push(graph, *pred)?;
}
}
Ok(Some((current, in_past)))
}
}