use std::mem::size_of;
use relate_core::RelId;
use crate::UsedSet;
use super::{
hop_count, merge_chunk, reclaim, SealedRegion, Supersede, Tombstone, COMPACTION_DELTA_FLOOR,
PHYSICAL_READ_TS, RESTORE_SEAL_HOPS, STABILITY_SEAL_FLOOR,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct AdjHop {
pub ts: i64,
pub id: RelId,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Hop {
pub ts: Option<i64>,
pub id: RelId,
}
fn resolve_one(h: &AdjHop, present: bool) -> Hop {
Hop {
ts: present.then_some(h.ts),
id: h.id,
}
}
pub(crate) fn resolve(hops: &[AdjHop], absent: u32, i: usize) -> Hop {
resolve_one(&hops[i], i >= absent as usize)
}
impl From<Hop> for AdjHop {
fn from(h: Hop) -> Self {
AdjHop {
ts: h.ts.unwrap_or(0),
id: h.id,
}
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct DeltaChunk {
pub type_id: u32,
absent: u32,
noted_len: u32,
held: bool,
pub hops: Vec<AdjHop>,
}
impl DeltaChunk {
pub(crate) fn absent_len(&self) -> u32 {
self.absent
}
pub(crate) fn remove_hop(&mut self, rid: RelId) -> bool {
let Some(i) = self.hops.iter().position(|h| h.id == rid) else {
return false;
};
self.hops.remove(i);
if i < self.absent as usize {
self.absent -= 1;
}
true
}
fn insert_hop(&mut self, hop: Hop) {
let absent = self.absent as usize;
let (range, decode): (std::ops::Range<usize>, fn(&AdjHop) -> Hop) = match hop.ts {
None => (0..absent, |h| resolve_one(h, false)),
Some(_) => (absent..self.hops.len(), |h| resolve_one(h, true)),
};
let start = range.start;
if let Err(i) = self.hops[range].binary_search_by(|h| cmp_ts_desc(&decode(h), &hop)) {
self.hops.insert(start + i, AdjHop::from(hop));
self.absent = hop_count(absent + usize::from(hop.ts.is_none()));
crate::memory::fit_hops_reserved(&mut self.hops);
}
}
fn set_baseline(&mut self, len: usize) {
let len = hop_count(len);
self.held = len != 0 && self.noted_len == len;
self.noted_len = len;
}
fn stability_due(&self) -> bool {
self.hops.len() >= STABILITY_SEAL_FLOOR
&& self.noted_len as usize == self.hops.len()
&& self.held
}
fn in_stability_band(&self, sealed_len: usize) -> bool {
sealed_len == 0
&& self.hops.len() >= STABILITY_SEAL_FLOOR
&& self.hops.len() < COMPACTION_DELTA_FLOOR
}
fn floor_admits_fold(&self) -> bool {
self.hops.len() >= COMPACTION_DELTA_FLOOR || self.stability_due()
}
fn to_hops(&self) -> Vec<Hop> {
(0..self.hops.len())
.map(|i| resolve(&self.hops, self.absent, i))
.collect()
}
fn take_hops(&mut self) -> Vec<Hop> {
let hops = self.to_hops();
self.absent = 0;
self.hops = Vec::new();
hops
}
fn set_hops(&mut self, hops: Vec<Hop>) {
let absent = hops.iter().take_while(|h| h.ts.is_none()).count();
debug_assert!(
!hops.iter().skip(absent).any(|h| h.ts.is_none()),
"absent hops are the chunk's head"
);
self.absent = hop_count(absent);
self.hops = hops.into_iter().map(AdjHop::from).collect();
crate::memory::fit_hops_reserved(&mut self.hops);
}
}
#[derive(Clone, Copy, Debug)]
enum FoldAction {
Fold,
Reclaim,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct FoldCandidate {
type_id: u32,
action: FoldAction,
}
fn due_action(
chunk: &DeltaChunk,
sealed: Option<SealedRegion<'_>>,
horizon: u64,
) -> Option<FoldAction> {
let type_id = chunk.type_id;
let delta = chunk.hops.len();
if let Some(region) = sealed {
if region.has_chunk(type_id) {
if region.reclaimable(type_id, horizon) {
let sealed_len = region.chunk_len(type_id);
return Some(if sealed_len == 0 && !chunk.floor_admits_fold() {
FoldAction::Reclaim
} else {
FoldAction::Fold
});
}
let len = region.chunk_len(type_id);
if len > 0 {
return (delta * 4 > len).then_some(FoldAction::Fold);
}
}
}
chunk.floor_admits_fold().then_some(FoldAction::Fold)
}
fn live_tombstones(
tombstones: Vec<Tombstone>,
sealed_ids: &UsedSet,
delta_ids: &UsedSet,
) -> Vec<Tombstone> {
tombstones
.into_iter()
.filter(|t| {
sealed_ids.contains(&t.id) || (t.deleted.is_some() && delta_ids.contains(&t.id))
})
.collect()
}
pub(crate) fn adjacency_bytes(chunk_hops: impl Iterator<Item = usize>) -> u64 {
let chunk_stride = size_of::<DeltaChunk>() as u64;
let hop_stride = size_of::<AdjHop>() as u64;
let mut chunks = 0usize;
let mut hop_bytes = 0u64;
for n in chunk_hops {
chunks += 1;
hop_bytes += crate::memory::vec_heap_hops(n, hop_stride);
}
crate::memory::vec_heap(chunks, chunk_stride) + hop_bytes
}
#[derive(Clone, Debug, Default)]
pub(crate) struct TypedAdj {
pub chunks: Vec<DeltaChunk>,
}
impl TypedAdj {
fn sealed_len(sealed: Option<SealedRegion<'_>>, type_id: u32) -> usize {
sealed.map_or(0, |s| s.chunk_len(type_id))
}
pub(crate) fn is_empty(&self) -> bool {
self.chunks.is_empty()
}
pub(crate) fn insert(&mut self, type_id: u32, rid: RelId, ts: Option<i64>) {
let hop = Hop { ts, id: rid };
if let Some(c) = self.chunk_mut(type_id) {
c.insert_hop(hop);
} else {
self.push_chunk(type_id, vec![hop]);
}
}
fn push_chunk(&mut self, type_id: u32, hops: Vec<Hop>) {
let mut chunk = DeltaChunk {
type_id,
..DeltaChunk::default()
};
chunk.set_hops(hops);
self.install_chunk(chunk);
}
fn install_chunk(&mut self, chunk: DeltaChunk) {
self.chunks.push(chunk);
crate::memory::fit_reserved(&mut self.chunks);
}
pub(crate) fn from_runs(
runs: impl IntoIterator<Item = (u32, Vec<Hop>)>,
mut seal: impl FnMut(u32, &[Hop]) -> bool,
) -> Self {
let mut runs: Vec<(RelId, u32, Vec<Hop>)> = 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(|c| c.type_id == type_id),
"one run per type"
);
hops.sort_unstable_by(cmp_ts_desc);
if hops.len() >= RESTORE_SEAL_HOPS && seal(type_id, &hops) {
typed.install_chunk(DeltaChunk {
type_id,
..DeltaChunk::default()
});
} else {
typed.push_chunk(type_id, hops);
}
}
typed
}
pub(crate) fn floor_bytes(&self) -> u64 {
adjacency_bytes(self.chunks.iter().map(|c| c.hops.len()))
}
pub(crate) fn reposition(
&mut self,
sealed: SealedRegion<'_>,
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);
self.insert(type_id, rid, ts);
}
pub(crate) fn remove(&mut self, sealed: Option<SealedRegion<'_>>, type_id: u32, rid: RelId) {
let Some(ci) = self.chunks.iter().position(|c| c.type_id == type_id) else {
return;
};
if !self.chunks[ci].remove_hop(rid) {
return;
}
let emptied = self.chunks[ci].hops.is_empty();
if emptied && Self::sealed_len(sealed, 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<SealedRegion<'_>>) -> Vec<RelId> {
let mut ids = Vec::new();
self.for_each_hop(sealed, PHYSICAL_READ_TS, |hop| ids.push(hop.id));
ids
}
#[cfg(test)]
pub(crate) fn chunk_hops(&self, type_id: u32) -> Vec<Hop> {
self.chunk_ref(type_id)
.map_or_else(Vec::new, DeltaChunk::to_hops)
}
fn chunk_ref(&self, type_id: u32) -> Option<&DeltaChunk> {
self.chunks.iter().find(|c| c.type_id == type_id)
}
pub(crate) fn total_len(&self, sealed: Option<SealedRegion<'_>>, type_id: u32) -> usize {
self.chunk_ref(type_id).map_or(0, |c| c.hops.len()) + Self::sealed_len(sealed, type_id)
}
pub(crate) fn chunk_lens<'a>(
&'a self,
sealed: Option<SealedRegion<'a>>,
) -> impl Iterator<Item = (u32, usize, usize)> + 'a {
self.chunks
.iter()
.map(move |c| (c.type_id, c.hops.len(), Self::sealed_len(sealed, c.type_id)))
}
pub(crate) fn for_each_hop_of(
&self,
sealed: Option<SealedRegion<'_>>,
type_id: u32,
ts: u64,
mut f: impl FnMut(Hop),
) {
visit_chunk(self.chunk_ref(type_id), sealed, type_id, ts, &mut f);
}
pub(crate) fn for_each_hop(
&self,
sealed: Option<SealedRegion<'_>>,
ts: u64,
mut f: impl FnMut(Hop),
) {
for chunk in &self.chunks {
visit_chunk(Some(chunk), sealed, chunk.type_id, ts, &mut f);
}
}
pub(crate) fn due_chunks(
&self,
sealed: Option<SealedRegion<'_>>,
horizon: u64,
) -> Vec<FoldCandidate> {
self.chunks
.iter()
.filter_map(|c| {
due_action(c, sealed, horizon).map(|action| FoldCandidate {
type_id: c.type_id,
action,
})
})
.collect()
}
pub(crate) fn note_stable(&mut self, sealed: Option<SealedRegion<'_>>) {
for chunk in &mut self.chunks {
let sealed_len = Self::sealed_len(sealed, chunk.type_id);
if chunk.in_stability_band(sealed_len) {
chunk.set_baseline(chunk.hops.len());
}
}
}
pub(crate) fn has_fold_work(&self, sealed: Option<SealedRegion<'_>>, horizon: u64) -> bool {
self.chunks.iter().any(|c| {
due_action(c, sealed, horizon).is_some()
|| c.in_stability_band(Self::sealed_len(sealed, c.type_id))
})
}
pub(crate) fn fold_at(&mut self, sealed: SealedRegion<'_>, horizon: u64) {
let candidates = self.due_chunks(Some(sealed), horizon);
self.fold_due(sealed, &candidates, horizon);
self.note_stable(Some(sealed));
}
fn fold_due(
&mut self,
sealed: SealedRegion<'_>,
candidates: &[FoldCandidate],
horizon: u64,
) -> bool {
let mut changed = false;
for candidate in candidates {
let ci = self
.chunks
.iter()
.position(|c| c.type_id == candidate.type_id)
.expect("a selected chunk is still present");
changed |= match candidate.action {
FoldAction::Reclaim => self.reclaim_orphans(sealed, ci),
FoldAction::Fold => self.fold_chunk(sealed, ci, horizon),
};
}
changed
}
fn fold_chunk(&mut self, sealed: SealedRegion<'_>, ci: usize, horizon: u64) -> bool {
let type_id = self.chunks[ci].type_id;
let mut delta = self.chunks[ci].take_hops();
let (mut hops, tombstones) = (sealed.decoded(type_id), sealed.tombstones(type_id));
if hops.is_empty() && delta.is_empty() && tombstones.is_empty() {
return false;
}
let (sealed_hops, sealed_tombstones) = (hops.len(), tombstones.len());
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 = live_tombstones(kept, &sealed_ids, &delta_ids);
let reclaimed = hops.len() != sealed_hops || kept.len() != sealed_tombstones;
if kept
.iter()
.any(|t| t.deleted != Some(t.xmax) && delta_ids.contains(&t.id))
{
let written = reclaimed && sealed.put_chunk(type_id, &hops, kept);
self.chunks[ci].set_hops(delta);
return written;
}
hops.extend_from_slice(&delta);
hops.sort_unstable_by(cmp_ts_desc);
if !sealed.put_chunk(type_id, &hops, kept) {
self.chunks[ci].set_hops(delta);
return false;
}
if hops.is_empty() {
self.chunks.remove(ci);
} else {
self.chunks[ci].set_baseline(0);
}
true
}
fn reclaim_orphans(&mut self, sealed: SealedRegion<'_>, ci: usize) -> bool {
let type_id = self.chunks[ci].type_id;
let tombstones = sealed.tombstones(type_id);
let sealed_tombstones = tombstones.len();
let delta_ids: UsedSet = self.chunks[ci].hops.iter().map(|h| h.id).collect();
let kept = live_tombstones(tombstones, &UsedSet::default(), &delta_ids);
if kept.len() == sealed_tombstones {
return false;
}
sealed.put_chunk(type_id, &[], kept)
}
fn chunk_mut(&mut self, type_id: u32) -> Option<&mut DeltaChunk> {
self.chunks.iter_mut().find(|c| c.type_id == type_id)
}
}
fn visit_chunk(
delta: Option<&DeltaChunk>,
sealed: Option<SealedRegion<'_>>,
type_id: u32,
ts: u64,
f: &mut impl FnMut(Hop),
) {
match sealed {
Some(region) => merge_chunk(delta, ®ion.visible_hops(type_id, ts), &mut *f),
None => merge_chunk(delta, &[], &mut *f),
}
}
pub(crate) fn cmp_ts_desc(a: &Hop, b: &Hop) -> 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)),
}
}
#[cfg(test)]
mod tests;