use std::mem::size_of;
use relate_core::RelId;
use crate::UsedSet;
use super::{
merge_chunk, reclaim, SealedRegion, Supersede, Tombstone, COMPACTION_DELTA_FLOOR,
PHYSICAL_READ_TS, RESTORE_SEAL_HOPS,
};
#[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,
}
pub(crate) fn resolve(hops: &[AdjHop], absent: u32, i: usize) -> Hop {
Hop {
ts: (i >= absent as usize).then_some(hops[i].ts),
id: hops[i].id,
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct DeltaChunk {
pub type_id: u32,
pub absent: u32,
pub hops: Vec<AdjHop>,
}
impl DeltaChunk {
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 = u32::try_from(absent).expect("adjacency chunk longer than u32::MAX hops");
self.hops = hops
.into_iter()
.map(|h| AdjHop {
ts: h.ts.unwrap_or(0),
id: h.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(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 {
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) {
insert_hop(c, 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);
crate::memory::fit_reserved(&mut chunk.hops);
self.chunks.push(chunk);
crate::memory::fit_reserved(&mut self.chunks);
}
pub(crate) fn from_runs(runs: impl IntoIterator<Item = (u32, Vec<Hop>)>) -> 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);
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;
};
let chunk = &mut self.chunks[ci];
let Some(i) = chunk.hops.iter().position(|h| h.id == rid) else {
return;
};
chunk.hops.remove(i);
if i < chunk.absent as usize {
chunk.absent -= 1;
}
let emptied = chunk.hops.is_empty();
if emptied && sealed.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<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())
+ sealed.map_or(0, |s| s.chunk_len(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(),
sealed.map_or(0, |s| s.chunk_len(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 chunk_due(
&self,
sealed: Option<SealedRegion<'_>>,
type_id: u32,
horizon: u64,
) -> bool {
let delta = self.chunk_ref(type_id).map_or(0, |c| c.hops.len());
if let Some(region) = sealed {
if region.has_chunk(type_id) {
if region.reclaimable(type_id, horizon) {
return true;
}
let len = region.chunk_len(type_id);
if len > 0 {
return delta * 4 > len;
}
}
}
delta >= COMPACTION_DELTA_FLOOR
}
pub(crate) fn due_chunks(&self, sealed: Option<SealedRegion<'_>>, horizon: u64) -> Vec<u32> {
self.chunks
.iter()
.map(|c| c.type_id)
.filter(|type_id| self.chunk_due(sealed, *type_id, horizon))
.collect()
}
pub(crate) fn sealable_chunks(&self) -> Vec<u32> {
self.chunks
.iter()
.filter(|c| c.hops.len() >= RESTORE_SEAL_HOPS)
.map(|c| c.type_id)
.collect()
}
pub(crate) fn fold_due(
&mut self,
sealed: SealedRegion<'_>,
due: &[u32],
horizon: u64,
floor: usize,
) -> bool {
let mut changed = false;
for type_id in due {
let ci = self
.chunks
.iter()
.position(|c| c.type_id == *type_id)
.expect("a due chunk is still present");
changed |= self.fold_chunk(sealed, ci, *type_id, horizon, floor);
}
changed
}
fn fold_chunk(
&mut self,
sealed: SealedRegion<'_>,
ci: usize,
type_id: u32,
horizon: u64,
floor: usize,
) -> bool {
let mut delta = self.chunks[ci].take_hops();
let (mut hops, tombstones) = if sealed.has_chunk(type_id) {
(sealed.decoded(type_id), sealed.tombstones(type_id))
} else {
(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() < 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].set_hops(delta);
return false;
}
self.chunks[ci].set_hops(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].set_hops(delta);
return false;
}
self.chunks[ci].set_hops(delta);
return reclaimed;
}
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);
}
true
}
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),
) {
let (raw, absent): (&[AdjHop], u32) = delta.map_or((&[], 0), |c| (&c.hops, c.absent));
match sealed {
Some(region) => merge_chunk(raw, absent, ®ion.visible_hops(type_id, ts), &mut *f),
None => {
for i in 0..raw.len() {
f(resolve(raw, absent, i));
}
}
}
}
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)),
}
}
fn insert_hop(chunk: &mut DeltaChunk, hop: Hop) {
let absent = chunk.absent as usize;
let pos = match hop.ts {
None => chunk.hops[..absent]
.binary_search_by(|h| cmp_ts_desc(&Hop { ts: None, id: h.id }, &hop)),
Some(_) => chunk.hops[absent..]
.binary_search_by(|h| {
cmp_ts_desc(
&Hop {
ts: Some(h.ts),
id: h.id,
},
&hop,
)
})
.map(|i| i + absent)
.map_err(|i| i + absent),
};
match pos {
Ok(_) => {}
Err(pos) => {
chunk.hops.insert(
pos,
AdjHop {
ts: hop.ts.unwrap_or(0),
id: hop.id,
},
);
chunk.absent += hop.ts.is_none() as u32;
crate::memory::fit_reserved(&mut chunk.hops);
}
}
}
#[cfg(test)]
mod tests;