use relate_core::RelId;
use crate::UsedSet;
use super::{
merge_chunk, reclaim, SealedAdj, SealedChunk, Supersede, Tombstone, COMPACTION_DELTA_FLOOR,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct AdjHop {
pub ts: Option<i64>,
pub id: RelId,
}
#[derive(Clone, Debug, Default)]
pub(crate) struct TypedAdj {
pub chunks: Vec<(u32, Vec<AdjHop>)>,
}
impl TypedAdj {
pub(crate) fn insert(&mut self, type_id: u32, rid: RelId, ts: Option<i64>) {
let hop = AdjHop { ts, id: rid };
if let Some(v) = self.chunk_mut(type_id) {
insert_hop(v, hop);
} else {
self.push_chunk(type_id, vec![hop]);
}
}
fn push_chunk(&mut self, type_id: u32, mut hops: Vec<AdjHop>) {
crate::memory::fit_reserved(&mut hops);
self.chunks.push((type_id, hops));
crate::memory::fit_reserved(&mut self.chunks);
}
pub(crate) fn from_runs(runs: impl IntoIterator<Item = (u32, Vec<AdjHop>)>) -> Self {
let mut runs: Vec<(RelId, u32, Vec<AdjHop>)> = runs
.into_iter()
.map(|(type_id, hops)| {
let first = hops.iter().map(|hop| hop.id).min().expect("a run has hops");
(first, type_id, hops)
})
.collect();
runs.sort_unstable_by_key(|&(first, _, _)| first);
let mut typed = Self::default();
for (_, type_id, mut hops) in runs {
debug_assert!(
!typed.chunks.iter().any(|(t, _)| *t == type_id),
"one run per type"
);
hops.sort_unstable_by(cmp_ts_desc);
typed.push_chunk(type_id, hops);
}
typed
}
pub(crate) fn floor_bytes(&self) -> u64 {
let hops: Vec<usize> = self.chunks.iter().map(|(_, v)| v.len()).collect();
crate::memory::adjacency_bytes(&hops)
}
pub(crate) fn reposition(
&mut self,
sealed: &mut SealedAdj,
type_id: u32,
rid: RelId,
ts: Option<i64>,
xmax: u64,
) {
sealed.tombstone_deleted(type_id, rid, xmax, Supersede::Repositioned);
self.remove(Some(sealed), type_id, rid);
if let Some(v) = self.chunk_mut(type_id) {
insert_hop(v, AdjHop { ts, id: rid });
} else {
self.insert(type_id, rid, ts);
}
}
pub(crate) fn remove(&mut self, sealed: Option<&mut SealedAdj>, type_id: u32, rid: RelId) {
let Some(ci) = self.chunks.iter().position(|(t, _)| *t == type_id) else {
return;
};
let v = &mut self.chunks[ci].1;
let Some(i) = v.iter().position(|h| h.id == rid) else {
return;
};
v.remove(i);
let emptied = v.is_empty();
if emptied && sealed.as_ref().map_or(0, |s| s.chunk_len(type_id)) == 0 {
self.chunks.remove(ci);
if let Some(sealed) = sealed {
sealed.put_chunk(type_id, &[], Vec::new());
}
}
}
pub(crate) fn flatten(&self, sealed: Option<&SealedAdj>) -> Vec<RelId> {
let mut ids = Vec::new();
self.for_each_hop(sealed, 0, |hop| ids.push(hop.id));
ids
}
pub(crate) fn chunk(&self, type_id: u32) -> &[AdjHop] {
self.chunks
.iter()
.find(|(t, _)| *t == type_id)
.map(|(_, v)| v.as_slice())
.unwrap_or(&[])
}
pub(crate) fn total_len(&self, sealed: Option<&SealedAdj>, type_id: u32) -> usize {
self.chunk(type_id).len() + sealed.map_or(0, |s| s.chunk_len(type_id))
}
pub(crate) fn chunk_lens<'a>(
&'a self,
sealed: Option<&'a SealedAdj>,
) -> impl Iterator<Item = (u32, usize, usize)> + 'a {
self.chunks.iter().map(move |(type_id, delta)| {
(
*type_id,
delta.len(),
sealed.map_or(0, |s| s.chunk_len(*type_id)),
)
})
}
pub(crate) fn for_each_hop_of(
&self,
sealed: Option<&SealedAdj>,
type_id: u32,
ts: u64,
mut f: impl FnMut(AdjHop),
) {
visit_chunk(
self.chunk(type_id),
sealed.and_then(|s| s.chunk(type_id)),
ts,
&mut f,
);
}
pub(crate) fn for_each_hop(
&self,
sealed: Option<&SealedAdj>,
ts: u64,
mut f: impl FnMut(AdjHop),
) {
for (type_id, delta) in &self.chunks {
visit_chunk(delta, sealed.and_then(|s| s.chunk(*type_id)), ts, &mut f);
}
}
pub(crate) fn chunk_due(&self, sealed: Option<&SealedAdj>, type_id: u32, horizon: u64) -> bool {
let delta = self.chunk(type_id).len();
match sealed.and_then(|s| s.chunk(type_id)) {
Some(chunk) if chunk.reclaimable(horizon) => true,
Some(chunk) if chunk.len() > 0 => delta * 4 > chunk.len(),
_ => delta >= COMPACTION_DELTA_FLOOR,
}
}
pub(crate) fn due_chunks(&self, sealed: Option<&SealedAdj>, horizon: u64) -> Vec<u32> {
self.chunks
.iter()
.map(|(type_id, _)| *type_id)
.filter(|type_id| self.chunk_due(sealed, *type_id, horizon))
.collect()
}
pub(crate) fn fold_due(&mut self, sealed: &mut SealedAdj, due: &[u32], horizon: u64) -> bool {
let mut changed = false;
for type_id in due {
if let Some(ci) = self.chunks.iter().position(|(t, _)| t == type_id) {
changed |= self.fold_chunk(sealed, ci, *type_id, horizon);
}
}
changed
}
fn fold_chunk(
&mut self,
sealed: &mut SealedAdj,
ci: usize,
type_id: u32,
horizon: u64,
) -> bool {
let mut delta = std::mem::take(&mut self.chunks[ci].1);
let (mut hops, tombstones) = match sealed.chunk(type_id) {
Some(chunk) => (chunk.decoded(), chunk.tombstones.clone()),
None => (Vec::new(), Vec::new()),
};
if hops.is_empty() && delta.is_empty() && tombstones.is_empty() {
return false;
}
let (sealed_hops, sealed_tombstones) = (hops.len(), tombstones.len());
if hops.is_empty() && delta.len() < COMPACTION_DELTA_FLOOR {
let delta_ids: UsedSet = delta.iter().map(|h| h.id).collect();
let kept: Vec<Tombstone> = tombstones
.into_iter()
.filter(|t| t.deleted.is_some() && delta_ids.contains(&t.id))
.collect();
let reclaimed = kept.len() != sealed_tombstones;
if reclaimed {
sealed.put_chunk(type_id, &[], kept);
}
self.chunks[ci].1 = delta;
return reclaimed;
}
let kept = reclaim(&mut hops, &mut delta, tombstones, horizon);
let sealed_ids: UsedSet = hops.iter().map(|h| h.id).collect();
let delta_ids: UsedSet = delta.iter().map(|h| h.id).collect();
let kept: Vec<Tombstone> = kept
.into_iter()
.filter(|t| {
sealed_ids.contains(&t.id) || (t.deleted.is_some() && delta_ids.contains(&t.id))
})
.collect();
let reclaimed = hops.len() != sealed_hops || kept.len() != sealed_tombstones;
if delta.iter().any(|h| {
kept.iter()
.any(|t| t.id == h.id && t.deleted != Some(t.xmax))
}) {
if reclaimed {
sealed.put_chunk(type_id, &hops, kept);
}
self.chunks[ci].1 = delta;
return reclaimed;
}
hops.extend(delta);
hops.sort_unstable_by(cmp_ts_desc);
if hops.is_empty() {
sealed.put_chunk(type_id, &hops, kept);
self.chunks.remove(ci);
return true;
}
sealed.put_chunk(type_id, &hops, kept);
true
}
fn chunk_mut(&mut self, type_id: u32) -> Option<&mut Vec<AdjHop>> {
self.chunks
.iter_mut()
.find(|(t, _)| *t == type_id)
.map(|(_, v)| v)
}
}
fn visit_chunk(
delta: &[AdjHop],
sealed: Option<&SealedChunk>,
ts: u64,
f: &mut impl FnMut(AdjHop),
) {
match sealed {
Some(sealed) => merge_chunk(delta, &sealed.visible_hops(ts), &mut *f),
None => {
for hop in delta {
f(*hop);
}
}
}
}
pub(crate) fn cmp_ts_desc(a: &AdjHop, b: &AdjHop) -> std::cmp::Ordering {
match (a.ts, b.ts) {
(None, None) => b.id.cmp(&a.id),
(None, Some(_)) => std::cmp::Ordering::Less,
(Some(_), None) => std::cmp::Ordering::Greater,
(Some(ta), Some(tb)) => tb.cmp(&ta).then(b.id.cmp(&a.id)),
}
}
fn insert_hop(v: &mut Vec<AdjHop>, hop: AdjHop) {
match v.binary_search_by(|h| cmp_ts_desc(h, &hop)) {
Ok(_) => {}
Err(pos) => {
v.insert(pos, hop);
crate::memory::fit_reserved(v);
}
}
}
#[cfg(test)]
mod tests;