use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::blocks::{BlockEntry, BlockError, BlockKind, Slot};
pub use crate::blocks::BLOCK;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct SealedId {
tree: u64,
index: u32,
}
impl SealedId {
pub fn index(&self) -> u32 { self.index }
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum InsertError {
NotFullBlock(usize),
WrongPosition { expected: usize, got: usize },
UnknownParent,
ForeignId,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct StartMatch<B> {
pub at: usize,
pub start: Option<SealedId>,
pub ids: Vec<SealedId>,
pub blocks: Vec<B>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct BlockHandles {
full: BlockEntry,
window: Option<BlockEntry>,
}
impl BlockHandles {
pub fn new(full: BlockEntry, window: Option<BlockEntry>) -> BlockHandles { BlockHandles { full, window } }
pub fn full(self) -> BlockEntry { self.full }
pub fn window(self) -> Option<BlockEntry> { self.window }
fn entries(self) -> impl Iterator<Item = BlockEntry> {
std::iter::once(self.full).chain(self.window)
}
}
pub type EntryTree = PrefixTree<BlockHandles>;
pub trait PrefixMatch<B> {
fn deepest_start(&self, tokens: &[u32]) -> StartMatch<B>;
}
struct Node<B> {
parent: Option<SealedId>,
pos: usize,
digest: u64,
tokens: Box<[u32]>,
handle: B,
starts: u32,
pins: u32,
children: Vec<SealedId>,
}
fn digest(parent: Option<SealedId>, pos: usize, tokens: &[u32]) -> u64 {
let mut h = 0xcbf29ce484222325u64;
let mut mix = |x: u64| h = (h ^ x).wrapping_mul(0x100000001b3);
mix(parent.map(|p| p.index as u64 + 1).unwrap_or(0));
mix(pos as u64);
for &t in tokens { mix(t as u64); }
h
}
static NEXT_TREE: AtomicU64 = AtomicU64::new(1);
pub struct PrefixTree<B> {
tree: u64,
nodes: Vec<Option<Node<B>>>,
roots: Vec<SealedId>,
by_digest: HashMap<u64, Vec<SealedId>>,
}
impl<B: Copy> PrefixTree<B> {
pub fn new() -> PrefixTree<B> {
PrefixTree { tree: NEXT_TREE.fetch_add(1, Ordering::Relaxed), nodes: Vec::new(), roots: Vec::new(), by_digest: HashMap::new() }
}
fn node(&self, id: SealedId) -> Option<&Node<B>> {
if id.tree != self.tree { return None; }
self.nodes.get(id.index as usize).and_then(|n| n.as_ref())
}
fn node_mut(&mut self, id: SealedId) -> Option<&mut Node<B>> {
if id.tree != self.tree { return None; }
self.nodes.get_mut(id.index as usize).and_then(|n| n.as_mut())
}
pub fn insert(&mut self, parent: Option<SealedId>, pos: usize, tokens: &[u32], handle: B) -> Result<SealedId, InsertError> {
if tokens.len() != BLOCK { return Err(InsertError::NotFullBlock(tokens.len())); }
let expected = match parent {
None => 0,
Some(p) => {
if p.tree != self.tree { return Err(InsertError::ForeignId); }
self.node(p).ok_or(InsertError::UnknownParent)?.pos + BLOCK
}
};
if pos != expected { return Err(InsertError::WrongPosition { expected, got: pos }); }
let d = digest(parent, pos, tokens);
if let Some(bucket) = self.by_digest.get(&d) {
for &id in bucket {
let n = self.node(id).expect("digest buckets hold live blocks");
if n.parent == parent && n.pos == pos && n.tokens.as_ref() == tokens { return Ok(id); }
}
}
let id = SealedId { tree: self.tree, index: self.nodes.len() as u32 };
self.nodes.push(Some(Node { parent, pos, digest: d, tokens: tokens.into(), handle, starts: 0, pins: 0, children: Vec::new() }));
match parent {
None => self.roots.push(id),
Some(p) => self.node_mut(p).expect("the parent was just checked").children.push(id),
}
self.by_digest.entry(d).or_default().push(id);
Ok(id)
}
fn find(&self, parent: Option<SealedId>, pos: usize, tokens: &[u32]) -> Option<SealedId> {
self.child(parent, pos, tokens)
}
pub fn entries(&self) -> Vec<(SealedId, B)> {
self.nodes.iter().enumerate()
.filter_map(|(i, n)| n.as_ref().map(|n| (SealedId { tree: self.tree, index: i as u32 }, n.handle)))
.collect()
}
pub fn retain_start(&mut self, id: SealedId) -> Result<bool, BlockError> {
match self.node_mut(id) {
Some(n) => {
n.starts = n.starts.checked_add(1).ok_or(BlockError::Overflow)?;
Ok(true)
}
None => Ok(false),
}
}
pub fn handle(&self, id: SealedId) -> Option<B> {
self.node(id).map(|n| n.handle)
}
pub fn set_handle(&mut self, id: SealedId, handle: B) -> bool {
match self.node_mut(id) {
Some(n) => { n.handle = handle; true }
None => false,
}
}
pub fn prune_unreferenced(&mut self, mut id: SealedId) -> usize {
let mut removed = 0usize;
while let Some(n) = self.node(id) {
if !n.children.is_empty() || n.starts > 0 || n.pins > 0 {
break;
}
let parent = n.parent;
self.remove(id);
removed += 1;
match parent {
Some(p) => id = p,
None => break,
}
}
removed
}
pub fn release_start(&mut self, id: SealedId) -> bool {
match self.node_mut(id) {
Some(n) if n.starts > 0 => { n.starts -= 1; true }
_ => false,
}
}
pub fn start_holders(&self, id: SealedId) -> u32 {
self.node(id).map(|n| n.starts).unwrap_or(0)
}
pub fn pin_count(&self, id: SealedId) -> u32 {
self.node(id).map(|n| n.pins).unwrap_or(0)
}
pub fn pin(&mut self, id: SealedId) -> Result<bool, BlockError> {
match self.node_mut(id) {
Some(n) => { n.pins = n.pins.checked_add(1).ok_or(BlockError::Overflow)?; Ok(true) }
None => Ok(false),
}
}
pub fn unpin(&mut self, id: SealedId) -> bool {
match self.node_mut(id) {
Some(n) if n.pins > 0 => { n.pins -= 1; true }
_ => false,
}
}
pub fn remove(&mut self, id: SealedId) -> Vec<B> {
self.remove_with_pins(id).into_iter().map(|(h, _)| h).collect()
}
pub fn remove_with_pins(&mut self, id: SealedId) -> Vec<(B, u32)> {
let Some(node) = self.node(id) else { return Vec::new() };
let parent = node.parent;
let mut gone = vec![id];
let mut i = 0;
while i < gone.len() {
let kids = self.node(gone[i]).map(|n| n.children.clone()).unwrap_or_default();
gone.extend(kids);
i += 1;
}
match parent {
None => self.roots.retain(|&r| r != id),
Some(p) => if let Some(n) = self.node_mut(p) { n.children.retain(|&c| c != id); },
}
let mut handles = Vec::new();
for g in gone {
let n = self.nodes[g.index as usize].take().expect("collected blocks are live");
if let Some(bucket) = self.by_digest.get_mut(&n.digest) {
bucket.retain(|&b| b != g);
if bucket.is_empty() { self.by_digest.remove(&n.digest); }
}
handles.push((n.handle, n.pins));
}
handles
}
fn child(&self, parent: Option<SealedId>, pos: usize, tokens: &[u32]) -> Option<SealedId> {
let bucket = self.by_digest.get(&digest(parent, pos, tokens))?;
for &id in bucket {
let n = self.node(id)?;
if n.parent == parent && n.pos == pos && n.tokens.as_ref() == tokens { return Some(id); }
}
None
}
}
impl<B: Copy> Default for PrefixTree<B> {
fn default() -> Self { Self::new() }
}
impl<B: Copy> PrefixMatch<B> for PrefixTree<B> {
fn deepest_start(&self, tokens: &[u32]) -> StartMatch<B> {
let mut best = StartMatch { at: 0, start: None, ids: Vec::new(), blocks: Vec::new() };
let mut parent = None;
let mut ids: Vec<SealedId> = Vec::new();
let mut chain: Vec<B> = Vec::new();
let mut at = 0usize;
while tokens.len() - at >= BLOCK {
let Some(id) = self.child(parent, at, &tokens[at..at + BLOCK]) else { break };
let n = self.node(id).expect("a child id names a live block");
ids.push(id);
chain.push(n.handle);
at += BLOCK;
parent = Some(id);
if n.starts > 0 {
best = StartMatch { at, start: Some(id), ids: ids.clone(), blocks: chain.clone() };
}
}
best
}
}
pub trait SlotRecords {
fn add_ref(&mut self, slot: Slot, kind: BlockKind, generation: u32) -> Result<(), BlockError>;
fn drop_ref(&mut self, slot: Slot, kind: BlockKind, generation: u32) -> Result<(), BlockError>;
fn generation(&self, slot: Slot, kind: BlockKind) -> Option<u32>;
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum LiveError {
Insert(InsertError),
Pool(BlockError),
StaleEntry { slot: Slot, claimed: u32, current: Option<u32> },
WrongKind { expected: BlockKind, got: BlockKind },
}
impl From<InsertError> for LiveError {
fn from(e: InsertError) -> LiveError { LiveError::Insert(e) }
}
impl From<BlockError> for LiveError {
fn from(e: BlockError) -> LiveError { LiveError::Pool(e) }
}
pub struct LiveTree<R> {
tree: EntryTree,
records: R,
}
impl<R: SlotRecords> LiveTree<R> {
pub fn new(records: R) -> LiveTree<R> {
LiveTree { tree: PrefixTree::new(), records }
}
fn check_current(&self, e: BlockEntry) -> Result<(), LiveError> {
match self.records.generation(e.slot(), e.kind()) {
Some(g) if g == e.generation() => Ok(()),
current => Err(LiveError::StaleEntry { slot: e.slot(), claimed: e.generation(), current }),
}
}
fn handles_current(&self, h: BlockHandles) -> Result<(), LiveError> {
for e in h.entries() { self.check_current(e)?; }
Ok(())
}
fn drop_ref_if_current(&mut self, e: BlockEntry) -> Result<(), LiveError> {
if self.records.generation(e.slot(), e.kind()) == Some(e.generation()) {
self.records.drop_ref(e.slot(), e.kind(), e.generation())?;
}
Ok(())
}
fn drop_pinned(&mut self, h: BlockHandles) -> Result<(), LiveError> {
for e in h.entries() { self.drop_ref_if_current(e)?; }
Ok(())
}
pub fn insert(&mut self, parent: Option<SealedId>, pos: usize, tokens: &[u32], handles: BlockHandles) -> Result<SealedId, LiveError> {
if handles.full.kind() != BlockKind::Full {
return Err(LiveError::WrongKind { expected: BlockKind::Full, got: handles.full.kind() });
}
if let Some(w) = handles.window {
if w.kind() != BlockKind::Window {
return Err(LiveError::WrongKind { expected: BlockKind::Window, got: w.kind() });
}
}
self.handles_current(handles)?;
if tokens.len() == BLOCK {
if let Some(id) = self.tree.find(parent, pos, tokens) {
let twin = self.tree.handle(id).expect("a found block has handles");
if self.handles_current(twin).is_ok() { return Ok(id); }
self.remove(id)?; }
}
Ok(self.tree.insert(parent, pos, tokens, handles)?)
}
pub fn pin(&mut self, id: SealedId) -> Result<bool, LiveError> {
let Some(handles) = self.tree.handle(id) else { return Ok(false) };
self.handles_current(handles)?;
if self.tree.pin_count(id) == 0 {
let mut taken: Vec<BlockEntry> = Vec::new();
for e in handles.entries() {
match self.records.add_ref(e.slot(), e.kind(), e.generation()) {
Ok(()) => taken.push(e),
Err(err) => {
for t in taken { let _ = self.drop_ref_if_current(t); }
return Err(err.into());
}
}
}
}
self.tree.pin(id)?;
Ok(true)
}
pub fn unpin(&mut self, id: SealedId) -> Result<bool, LiveError> {
let Some(handles) = self.tree.handle(id) else { return Ok(false) };
if self.tree.pin_count(id) == 0 { return Ok(false); }
if self.tree.pin_count(id) == 1 { self.drop_pinned(handles)?; }
Ok(self.tree.unpin(id))
}
pub fn pin_count(&self, id: SealedId) -> u32 { self.tree.pin_count(id) }
pub fn retain_start(&mut self, id: SealedId) -> Result<bool, BlockError> { self.tree.retain_start(id) }
pub fn release_start(&mut self, id: SealedId) -> bool { self.tree.release_start(id) }
pub fn handle(&self, id: SealedId) -> Option<BlockHandles> { self.tree.handle(id) }
pub fn remove(&mut self, id: SealedId) -> Result<Vec<BlockHandles>, LiveError> {
let removed = self.tree.remove_with_pins(id);
let mut first_err = None;
for (h, pins) in &removed {
if *pins > 0 {
if let Err(e) = self.drop_pinned(*h) {
if first_err.is_none() { first_err = Some(e); }
}
}
}
let handles: Vec<BlockHandles> = removed.into_iter().map(|(h, _)| h).collect();
match first_err {
None => Ok(handles),
Some(e) => Err(e),
}
}
pub fn deepest_start(&mut self, tokens: &[u32]) -> Result<StartMatch<BlockHandles>, LiveError> {
let stale: Vec<SealedId> = self.tree.entries().into_iter()
.filter(|(_, h)| h.entries().any(|e| self.records.generation(e.slot(), e.kind()) != Some(e.generation())))
.map(|(id, _)| id)
.collect();
for id in stale {
self.remove(id)?;
}
let m = self.tree.deepest_start(tokens);
if !tokens.is_empty() && m.at == tokens.len() {
return Ok(self.tree.deepest_start(&tokens[..tokens.len() - BLOCK]));
}
Ok(m)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::blocks::SlotRecord;
fn block(seed: u32) -> Vec<u32> { (0..BLOCK as u32).map(|i| seed * 1000 + i).collect() }
fn tree3() -> (PrefixTree<u64>, Vec<SealedId>) {
let mut t = PrefixTree::new();
let a = t.insert(None, 0, &block(1), 10).unwrap();
let b = t.insert(Some(a), BLOCK, &block(2), 20).unwrap();
let c = t.insert(Some(b), 2 * BLOCK, &block(3), 30).unwrap();
(t, vec![a, b, c])
}
#[test]
fn an_empty_tree_starts_at_zero() {
let t: PrefixTree<u64> = PrefixTree::new();
let m = t.deepest_start(&block(1));
assert_eq!(m, StartMatch { at: 0, start: None, ids: vec![], blocks: vec![] });
}
#[test]
fn the_deepest_retained_start_point_wins() {
let (mut t, ids) = tree3();
t.retain_start(ids[0]).unwrap();
t.retain_start(ids[2]).unwrap();
let toks = [block(1), block(2), block(3), block(9)].concat();
let m = t.deepest_start(&toks);
assert_eq!(m.at, 3 * BLOCK);
assert_eq!(m.start, Some(ids[2]));
assert_eq!(m.ids, ids);
assert_eq!(m.blocks, vec![10, 20, 30], "handles from the root to the start point, in order");
}
#[test]
fn start_points_are_counted_not_boolean() {
let (mut t, ids) = tree3();
t.retain_start(ids[2]).unwrap();
t.retain_start(ids[2]).unwrap();
assert_eq!(t.start_holders(ids[2]), 2);
let toks = [block(1), block(2), block(3)].concat();
assert!(t.release_start(ids[2]), "the lane head lets go");
assert_eq!(t.deepest_start(&toks).at, 3 * BLOCK, "the prompt end still holds it");
assert!(t.release_start(ids[2]));
assert_eq!(t.deepest_start(&toks).at, 0, "the last release unmatches it");
assert!(!t.release_start(ids[2]), "no holder left to release");
}
#[test]
fn a_block_that_differs_anywhere_stops_the_match() {
let (mut t, ids) = tree3();
t.retain_start(ids[2]).unwrap();
let mut second = block(2);
second[63] ^= 1;
let toks = [block(1), second, block(3)].concat();
assert_eq!(t.deepest_start(&toks).at, 0, "the second block differs, so even the third block's start point is unreachable");
let (mut t2, ids2) = tree3();
t2.retain_start(ids2[1]).unwrap();
assert_eq!(t2.deepest_start(&[block(1), block(7)].concat()).at, 0);
}
#[test]
fn equal_local_tokens_under_different_parents_are_different_blocks() {
let mut t: PrefixTree<u64> = PrefixTree::new();
let a = t.insert(None, 0, &block(1), 10).unwrap();
let x = t.insert(None, 0, &block(5), 50).unwrap();
let a2 = t.insert(Some(a), BLOCK, &block(2), 20).unwrap();
let x2 = t.insert(Some(x), BLOCK, &block(2), 60).unwrap();
assert_ne!(a2, x2);
t.retain_start(a2).unwrap();
t.retain_start(x2).unwrap();
assert_eq!(t.deepest_start(&[block(5), block(2)].concat()).blocks, vec![50, 60],
"the match follows the parent chain, never the local tokens alone");
assert_eq!(t.deepest_start(&[block(1), block(2)].concat()).blocks, vec![10, 20]);
}
#[test]
fn racing_publishers_dedupe_only_on_exact_tokens() {
let mut t: PrefixTree<u64> = PrefixTree::new();
let a = t.insert(None, 0, &block(1), 10).unwrap();
assert_eq!(t.insert(None, 0, &block(1), 99), Ok(a), "the same block again is the canonical one, with its first handle");
assert_ne!(t.insert(None, 0, &block(2), 20).unwrap(), a, "different tokens are a different root");
}
#[test]
fn unsealed_misplaced_and_foreign_blocks_never_enter() {
let mut t: PrefixTree<u64> = PrefixTree::new();
let mut other: PrefixTree<u64> = PrefixTree::new();
let foreign = other.insert(None, 0, &block(1), 1).unwrap();
assert_eq!(t.insert(None, 0, &block(1)[..63], 10), Err(InsertError::NotFullBlock(63)), "a partial tail is unsealed");
assert_eq!(t.insert(None, BLOCK, &block(1), 10), Err(InsertError::WrongPosition { expected: 0, got: BLOCK }));
assert_eq!(t.insert(Some(foreign), BLOCK, &block(1), 10), Err(InsertError::ForeignId),
"an id from another tree names nothing here, even at an existing index");
assert_eq!(t.retain_start(foreign), Ok(false), "a foreign id is no block here");
assert!(t.remove(foreign).is_empty());
let a = t.insert(None, 0, &block(1), 10).unwrap();
assert_eq!(t.insert(Some(a), 0, &block(2), 20), Err(InsertError::WrongPosition { expected: BLOCK, got: 0 }));
t.remove(a);
assert_eq!(t.insert(Some(a), BLOCK, &block(2), 20), Err(InsertError::UnknownParent));
}
#[test]
fn remove_shrinks_the_tree_and_returns_handles() {
let (mut t, ids) = tree3();
t.retain_start(ids[2]).unwrap();
let toks = [block(1), block(2), block(3)].concat();
assert_eq!(t.remove(ids[1]), vec![20, 30], "the block and everything below it, root-first");
assert_eq!(t.deepest_start(&toks).at, 0);
assert!(t.remove(ids[1]).is_empty(), "already gone");
let b = t.insert(Some(ids[0]), BLOCK, &block(2), 21).unwrap();
assert_ne!(b, ids[1], "ids are never reused");
t.retain_start(b).unwrap();
assert_eq!(t.deepest_start(&toks).blocks, vec![10, 21]);
}
#[test]
fn a_partial_final_block_and_sixteen_block_starts() {
let mut t: PrefixTree<u64> = PrefixTree::new();
let mut parent = None;
let mut ids = Vec::new();
for i in 0..17u32 {
let id = t.insert(parent, i as usize * BLOCK, &block(i + 1), i as u64).unwrap();
ids.push(id);
parent = Some(id);
}
t.retain_start(ids[15]).unwrap(); let mut toks: Vec<u32> = (1..=17u32).flat_map(block).collect();
assert_eq!(t.deepest_start(&toks).at, 16 * BLOCK);
toks.truncate(16 * BLOCK + 63);
let m = t.deepest_start(&toks);
assert_eq!(m.at, 16 * BLOCK, "63 tokens into block 17 is not a block");
assert_eq!(m.blocks.len(), 16);
}
#[derive(Default)]
struct FakeRecords { map: HashMap<(u32, bool), SlotRecord> }
impl FakeRecords {
fn key(slot: Slot, kind: BlockKind) -> (u32, bool) { (slot.get(), kind == BlockKind::Full) }
fn record(&mut self, slot: Slot, kind: BlockKind) -> &mut SlotRecord {
self.map.entry(Self::key(slot, kind)).or_insert_with(|| {
let mut r = SlotRecord::fresh(kind);
r.bump_generation().unwrap();
r
})
}
fn refs(&mut self, slot: Slot, kind: BlockKind) -> u32 { self.record(slot, kind).refs() }
fn pool_refs(&self, slot: Slot, kind: BlockKind) -> u32 {
self.map.get(&Self::key(slot, kind)).map(|r| r.refs()).unwrap_or(0)
}
fn reuse(&mut self, slot: Slot, kind: BlockKind) {
let r = self.record(slot, kind);
while r.refs() > 0 { r.drop_ref().unwrap(); }
r.reissue().unwrap();
}
}
impl SlotRecords for FakeRecords {
fn add_ref(&mut self, slot: Slot, kind: BlockKind, generation: u32) -> Result<(), BlockError> {
if self.generation(slot, kind) != Some(generation) { return Err(BlockError::Generation); }
self.record(slot, kind).add_ref()
}
fn drop_ref(&mut self, slot: Slot, kind: BlockKind, generation: u32) -> Result<(), BlockError> {
if self.generation(slot, kind) != Some(generation) { return Err(BlockError::Generation); }
self.record(slot, kind).drop_ref()
}
fn generation(&self, slot: Slot, kind: BlockKind) -> Option<u32> {
Some(self.map.get(&Self::key(slot, kind)).map(|r| r.generation()).unwrap_or(1))
}
}
fn entry(slot: u32, generation: u32, kind: BlockKind) -> BlockEntry {
BlockEntry::new(Slot::new(slot).unwrap(), generation, 4096, kind, 2)
}
fn handles(slot: u32, generation: u32) -> BlockHandles {
BlockHandles::new(entry(slot, generation, BlockKind::Full), None)
}
fn handles_win(slot: u32, generation: u32, wslot: u32, wgen: u32) -> BlockHandles {
BlockHandles::new(entry(slot, generation, BlockKind::Full), Some(entry(wslot, wgen, BlockKind::Window)))
}
#[test]
fn a_reused_slots_stale_entry_is_a_miss_never_a_match() {
let mut live = LiveTree::new(FakeRecords::default());
let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
let b = live.insert(Some(a), BLOCK, &block(2), handles(4, 1)).unwrap();
live.retain_start(b).unwrap();
let toks = [block(1), block(2)].concat();
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "a cached block sits at zero refs");
live.pin(a).unwrap();
live.pin(b).unwrap();
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 1, "the first pin took the ref");
live.retain_start(a).unwrap();
assert_eq!(live.deepest_start(&toks).unwrap().at, BLOCK, "exact full match steps back one block");
live.records.reuse(Slot::new(3).unwrap(), BlockKind::Full); let m = live.deepest_start(&toks).unwrap();
assert_eq!(m.at, 0, "the gen-1 entry for a gen-2 slot is stale: a miss, not a match");
assert_eq!(live.deepest_start(&toks).unwrap().at, 0, "and it was evicted, not rechecked forever");
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "no ref leaks on the reused slot");
assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Full), 0, "the evicted child's pinned ref was dropped too");
let a2 = live.insert(None, 0, &block(1), handles(3, 2)).unwrap();
live.retain_start(a2).unwrap();
assert_eq!(live.deepest_start(&block(1)).unwrap().at, 0, "one block is the whole prompt: the suffix is never empty");
assert_eq!(live.deepest_start(&[block(1), block(9)].concat()).unwrap().blocks, vec![handles(3, 2)]);
}
#[test]
fn a_fresh_block_is_never_lost_to_its_stale_twin() {
let mut live = LiveTree::new(FakeRecords::default());
let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
live.pin(a).unwrap();
live.records.reuse(Slot::new(3).unwrap(), BlockKind::Full); let a2 = live.insert(None, 0, &block(1), handles(3, 2)).unwrap();
assert_ne!(a2, a, "the fresh block is a new block, not the stale twin");
assert_eq!(live.pin_count(a2), 0, "the fresh block starts unpinned");
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0,
"the twin's pin died with its generation; no blind drop touched the new owner");
live.pin(a2).unwrap();
live.retain_start(a2).unwrap();
assert_eq!(live.deepest_start(&[block(1), block(9)].concat()).unwrap().blocks, vec![handles(3, 2)],
"and the fresh block survives the next seek");
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 1);
}
#[test]
fn a_stale_entry_is_refused_at_insert() {
let mut live = LiveTree::new(FakeRecords::default());
let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
live.records.reuse(Slot::new(3).unwrap(), BlockKind::Full); let stale = LiveError::StaleEntry { slot: Slot::new(3).unwrap(), claimed: 1, current: Some(2) };
assert_eq!(live.insert(None, 0, &block(9), handles(3, 1)), Err(stale.clone()),
"a gen-1 entry for a gen-2 slot is refused, not inserted");
assert_eq!(live.insert(None, 0, &block(1), handles(3, 1)), Err(stale),
"the same refusal when the tokens are already in the tree");
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "no ref was taken by either refusal");
assert_eq!(live.handle(a), Some(handles(3, 1)), "the tree is unchanged");
assert!(live.insert(None, 0, &block(9), handles(3, 2)).is_ok());
}
#[test]
fn a_seek_evicts_stale_blocks_off_the_matched_path() {
let mut live = LiveTree::new(FakeRecords::default());
let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
let off = live.insert(None, 0, &block(7), handles(4, 1)).unwrap();
live.retain_start(a).unwrap();
live.pin(off).unwrap();
live.records.reuse(Slot::new(4).unwrap(), BlockKind::Full); let m = live.deepest_start(&[block(1), block(9)].concat()).unwrap();
assert_eq!(m.at, BLOCK, "the live path still matches");
assert_eq!(live.handle(off), None, "the stale off-path block was evicted by the seek");
assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Full), 0, "and no ref is left on the reused slot");
}
#[test]
fn pins_take_and_drop_one_ref_per_block() {
let mut live = LiveTree::new(FakeRecords::default());
let a = live.insert(None, 0, &block(1), handles_win(3, 1, 4, 1)).unwrap();
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "idle: no Full ref");
assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Window), 0, "idle: no Window ref");
live.pin(a).unwrap();
live.pin(a).unwrap();
assert_eq!(live.pin_count(a), 2);
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 1, "two pins, one Full ref");
assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Window), 1, "two pins, one Window ref");
assert_eq!(live.handle(a).unwrap().window(), Some(entry(4, 1, BlockKind::Window)), "both entries ride on the node");
live.unpin(a).unwrap();
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 1, "a pin remains");
live.unpin(a).unwrap();
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "the last unpin dropped the Full ref");
assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Window), 0, "and the Window ref");
assert_eq!(live.unpin(a), Ok(false), "no pin left to drop");
live.pin(a).unwrap();
let gone = live.remove(a).unwrap();
assert_eq!(gone, vec![handles_win(3, 1, 4, 1)]);
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0);
}
#[test]
fn a_reused_slots_new_owner_keeps_its_refcount() {
let mut live = LiveTree::new(FakeRecords::default());
let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
live.pin(a).unwrap();
live.records.reuse(Slot::new(3).unwrap(), BlockKind::Full); live.records.add_ref(Slot::new(3).unwrap(), BlockKind::Full, 2).unwrap(); live.remove(a).unwrap();
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 1,
"the stale block's eviction skipped the drop: the new owner's ref stands");
assert_eq!(live.records.drop_ref(Slot::new(3).unwrap(), BlockKind::Full, 1), Err(BlockError::Generation));
}
#[test]
fn live_inserts_and_removes_balance_their_refs() {
let mut live = LiveTree::new(FakeRecords::default());
let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
assert_eq!(live.insert(None, 0, &block(1), handles(3, 1)), Ok(a), "a racing publisher dedupes");
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "and still takes no ref");
assert!(live.insert(Some(a), 0, &block(2), handles(4, 1)).is_err());
assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Full), 0);
live.pin(a).unwrap();
let gone = live.remove(a).unwrap();
assert_eq!(gone, vec![handles(3, 1)]);
assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "removal dropped the pinned ref");
}
fn enc(block: [u32; 2]) -> Vec<u32> {
let mut v = vec![block[0]; BLOCK / 2];
v.extend([block[1]; BLOCK / 2]);
v
}
fn tla_seq(s: &[u32]) -> String {
let inner: Vec<String> = s.iter().map(|t| t.to_string()).collect();
format!("<<{}>>", inner.join(", "))
}
fn tla_universe() -> Vec<Vec<u32>> {
let mut u = vec![Vec::new()];
for a in 1..=2 { for b in 1..=2 { u.push(vec![a, b]); } }
for a in 1..=2 { for b in 1..=2 { for c in 1..=2 { for d in 1..=2 { u.push(vec![a, b, c, d]); } } } }
u
}
fn tla_fn(values: &HashMap<Vec<u32>, i64>) -> String {
let cases: Vec<String> = tla_universe().iter()
.filter(|s| values.get(*s).copied().unwrap_or(0) != 0)
.map(|s| format!("s = {} -> {}", tla_seq(s), values[s]))
.collect();
if cases.is_empty() { return "[s \\in BlockSeqs |-> 0]".to_string(); }
format!("[s \\in BlockSeqs |-> CASE {} [] OTHER -> 0]", cases.join(" [] "))
}
#[test]
#[ignore = "trace dump; run by specs/run_tlc.zsh"]
fn prefix_trace_dump() {
let out = std::env::var("INKY_PREFIX_TRACE_OUT")
.unwrap_or_else(|_| "specs/PrefixTreeTraceData.tla".to_string());
let mut live = LiveTree::new(FakeRecords::default());
let mut seq_of: HashMap<SealedId, Vec<u32>> = HashMap::new();
let mut rows: Vec<String> = Vec::new();
let mut random: u64 = 0x9e3779b97f4a7c15;
let mut pick = move |n: usize| -> usize {
random = random.wrapping_mul(6364136223846793005).wrapping_add(1);
(random >> 32) as usize % n
};
let snapshot = |live: &LiveTree<FakeRecords>, seq_of: &HashMap<SealedId, Vec<u32>>,
op: &str, s: &[u32], slot: u32, wslot: u32, result: &[u32], sought: bool| -> String {
let mut sealed: Vec<String> = vec![tla_seq(&[])];
let (mut starts, mut slot_of_m, mut gen_of, mut win_slot, mut win_gen, mut refs) =
(HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new());
for (id, h) in live.tree.entries() {
let seq = seq_of[&id].clone();
sealed.push(tla_seq(&seq));
starts.insert(seq.clone(), live.tree.start_holders(id) as i64);
slot_of_m.insert(seq.clone(), h.full().slot().get() as i64);
gen_of.insert(seq.clone(), h.full().generation() as i64 - 1);
if let Some(w) = h.window() {
win_slot.insert(seq.clone(), w.slot().get() as i64);
win_gen.insert(seq.clone(), w.generation() as i64 - 1);
}
if live.pin_count(id) > 0 { refs.insert(seq, 1); }
}
let pr = |sl: u32| live.records.pool_refs(Slot::new(sl).unwrap(), BlockKind::Full)
+ live.records.pool_refs(Slot::new(sl).unwrap(), BlockKind::Window);
let pool_refs = format!("[s \\in Slots |-> IF s = 1 THEN {} ELSE IF s = 2 THEN {} ELSE {}]", pr(1), pr(2), pr(3));
let g = |sl: u32| live.records.generation(Slot::new(sl).unwrap(), BlockKind::Full).unwrap() - 1;
let pool = format!("[s \\in Slots |-> IF s = 1 THEN {} ELSE IF s = 2 THEN {} ELSE {}]", g(1), g(2), g(3));
format!(
"[op |-> \"{op}\", s |-> {}, slot |-> {slot}, wslot |-> {wslot}, sealed |-> {{{}}}, starts |-> {}, \
slotOf |-> {}, genOf |-> {}, winSlotOf |-> {}, winGenOf |-> {}, poolGen |-> {}, refs |-> {}, poolRefs |-> {}, result |-> {}, sought |-> {}, bad |-> FALSE]",
tla_seq(s), sealed.join(", "), tla_fn(&starts), tla_fn(&slot_of_m),
tla_fn(&gen_of), tla_fn(&win_slot), tla_fn(&win_gen), pool, tla_fn(&refs), pool_refs, tla_seq(result),
if sought { "TRUE" } else { "FALSE" })
};
let req_abstract: Vec<u32> = vec![1, 2, 1, 2];
let req: Vec<u32> = [enc([1, 2]), enc([1, 2])].concat();
let pair = |live: &LiveTree<FakeRecords>, slot: u32, wslot: u32| -> BlockHandles {
let fg = live.records.generation(Slot::new(slot).unwrap(), BlockKind::Full).unwrap();
let wg = live.records.generation(Slot::new(wslot).unwrap(), BlockKind::Window).unwrap();
handles_win(slot, fg, wslot, wg)
};
rows.push(snapshot(&live, &seq_of, "init", &[], 0, 0, &[], false));
let root = live.insert(None, 0, &enc([1, 2]), pair(&live, 1, 3)).unwrap();
seq_of.insert(root, vec![1, 2]);
rows.push(snapshot(&live, &seq_of, "seal", &[1, 2], 1, 3, &[], false));
let child = live.insert(Some(root), BLOCK, &enc([1, 2]), pair(&live, 2, 1)).unwrap();
seq_of.insert(child, req_abstract.clone());
rows.push(snapshot(&live, &seq_of, "seal", &req_abstract, 2, 1, &[], false));
live.retain_start(root).unwrap();
rows.push(snapshot(&live, &seq_of, "retain", &[1, 2], 0, 0, &[], false));
live.retain_start(child).unwrap();
rows.push(snapshot(&live, &seq_of, "retain", &req_abstract, 0, 0, &[], false));
live.pin(root).unwrap();
rows.push(snapshot(&live, &seq_of, "pin", &[1, 2], 0, 0, &[], false));
live.pin(child).unwrap();
rows.push(snapshot(&live, &seq_of, "pin", &req_abstract, 0, 0, &[], false));
let m = live.deepest_start(&req).unwrap();
rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));
assert!(live.release_start(root));
rows.push(snapshot(&live, &seq_of, "release", &[1, 2], 0, 0, &[], false));
live.unpin(child).unwrap();
rows.push(snapshot(&live, &seq_of, "unpin", &req_abstract, 0, 0, &[], false));
let m = live.deepest_start(&req).unwrap();
rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));
live.unpin(root).unwrap();
rows.push(snapshot(&live, &seq_of, "unpin", &[1, 2], 0, 0, &[], false));
live.records.reuse(Slot::new(1).unwrap(), BlockKind::Full);
live.records.reuse(Slot::new(1).unwrap(), BlockKind::Window);
rows.push(snapshot(&live, &seq_of, "reuse", &[], 1, 0, &[], false));
let m = live.deepest_start(&req).unwrap();
rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));
let root2 = live.insert(None, 0, &enc([1, 2]), pair(&live, 3, 2)).unwrap();
seq_of.insert(root2, vec![1, 2]);
rows.push(snapshot(&live, &seq_of, "seal", &[1, 2], 3, 2, &[], false));
live.retain_start(root2).unwrap();
rows.push(snapshot(&live, &seq_of, "retain", &[1, 2], 0, 0, &[], false));
live.records.reuse(Slot::new(3).unwrap(), BlockKind::Full);
live.records.reuse(Slot::new(3).unwrap(), BlockKind::Window);
rows.push(snapshot(&live, &seq_of, "reuse", &[], 3, 0, &[], false));
let fresh = pair(&live, 2, 1);
let root3 = live.insert(None, 0, &enc([1, 2]), fresh).unwrap();
assert_ne!(root3, root2, "the fresh block replaces the stale twin");
seq_of.retain(|id, _| *id != root2);
seq_of.insert(root3, vec![1, 2]);
rows.push(snapshot(&live, &seq_of, "seal-twin", &[1, 2], 2, 1, &[], false));
live.retain_start(root3).unwrap();
rows.push(snapshot(&live, &seq_of, "retain", &[1, 2], 0, 0, &[], false));
live.pin(root3).unwrap();
rows.push(snapshot(&live, &seq_of, "pin", &[1, 2], 0, 0, &[], false));
let m = live.deepest_start(&req).unwrap();
rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));
let mut mutating = 0;
let mut attempts = 0;
while mutating < 40 && attempts < 500 {
attempts += 1;
let live_ids: Vec<SealedId> = live.tree.entries().into_iter().map(|(id, _)| id).collect();
seq_of.retain(|id, _| live_ids.contains(id));
match pick(10) {
0 => { let parents: Vec<Option<SealedId>> = std::iter::once(None)
.chain(live_ids.iter().filter(|id| seq_of[id].len() == 2).map(|id| Some(*id)))
.collect();
let parent = parents[pick(parents.len())];
let base: Vec<u32> = parent.map(|p| seq_of[&p].clone()).unwrap_or_default();
let block = [1 + pick(2) as u32, 1 + pick(2) as u32];
let mut seq = base.clone();
seq.extend(block);
if seq_of.values().any(|s| *s == seq) { continue; }
let slot = 1 + pick(3) as u32;
let wslot = 1 + (slot + pick(2) as u32) % 3;
let id = live.insert(parent, base.len() / 2 * BLOCK, &enc(block),
pair(&live, slot, wslot)).expect("a fresh seal at the current generations");
seq_of.insert(id, seq.clone());
rows.push(snapshot(&live, &seq_of, "seal", &seq, slot, wslot, &[], false));
}
1 => { let slot = 1 + pick(3) as u32;
let gen = live.records.generation(Slot::new(slot).unwrap(), BlockKind::Full).unwrap();
if gen < 2 { continue; }
let block = [1 + pick(2) as u32, 1 + pick(2) as u32];
let got = live.insert(None, 0, &enc(block), handles(slot, gen - 1));
assert_eq!(got, Err(LiveError::StaleEntry {
slot: Slot::new(slot).unwrap(), claimed: gen - 1, current: Some(gen) }),
"the walk's stale insert is refused");
rows.push(snapshot(&live, &seq_of, "seal-stale", &block.to_vec(), slot, 0, &[], false));
}
2 => { let held: Vec<SealedId> = live_ids.iter().copied()
.filter(|id| live.tree.start_holders(*id) < 2).collect();
if held.is_empty() { continue; }
let id = held[pick(held.len())];
live.retain_start(id).unwrap();
let seq = seq_of[&id].clone();
rows.push(snapshot(&live, &seq_of, "retain", &seq, 0, 0, &[], false));
}
3 => { let held: Vec<SealedId> = live_ids.iter().copied()
.filter(|id| live.tree.start_holders(*id) > 0).collect();
if held.is_empty() { continue; }
let id = held[pick(held.len())];
assert!(live.release_start(id));
let seq = seq_of[&id].clone();
rows.push(snapshot(&live, &seq_of, "release", &seq, 0, 0, &[], false));
}
4 => { let slot = 1 + pick(3) as u32;
let gen = live.records.generation(Slot::new(slot).unwrap(), BlockKind::Full).unwrap();
if gen >= 3 { continue; }
let pinned_slots: Vec<u32> = live.tree.entries().into_iter()
.filter(|(id, _)| live.pin_count(*id) > 0)
.flat_map(|(_, h)| h.entries().map(|e| e.slot().get()).collect::<Vec<_>>())
.collect();
if pinned_slots.contains(&slot) { continue; }
live.records.reuse(Slot::new(slot).unwrap(), BlockKind::Full);
live.records.reuse(Slot::new(slot).unwrap(), BlockKind::Window);
rows.push(snapshot(&live, &seq_of, "reuse", &[], slot, 0, &[], false));
}
5 => { if live_ids.is_empty() { continue; }
let id = live_ids[pick(live_ids.len())];
let seq = seq_of[&id].clone();
let twin = live.handle(id).unwrap();
let (parent, pos) = if seq.len() == 2 { (None, 0) } else {
let pid = *seq_of.iter().find(|(_, s)| **s == seq[..2]).unwrap().0;
(Some(pid), BLOCK)
};
let block = [seq[seq.len() - 2], seq[seq.len() - 1]];
let current = |e: BlockEntry| live.records.generation(e.slot(), e.kind()) == Some(e.generation());
if current(twin.full()) && twin.window().map(current).unwrap_or(true) {
let got = live.insert(parent, pos, &enc(block), twin).unwrap();
assert_eq!(got, id, "the dedup returns the block already in the tree");
rows.push(snapshot(&live, &seq_of, "seal-dup", &seq, twin.full().slot().get(), twin.window().map(|w| w.slot().get()).unwrap_or(0), &[], false));
} else {
let slot = 1 + pick(3) as u32;
let wslot = 1 + (slot + pick(2) as u32) % 3;
let fresh = live.insert(parent, pos, &enc(block), pair(&live, slot, wslot)).unwrap();
assert_ne!(fresh, id, "the fresh block replaces the stale twin");
seq_of.retain(|k, _| *k != id);
seq_of.insert(fresh, seq.clone());
rows.push(snapshot(&live, &seq_of, "seal-twin", &seq, slot, wslot, &[], false));
}
}
6 => { let m = live.deepest_start(&req).unwrap();
rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));
}
7 => { let cand: Vec<SealedId> = live_ids.iter().copied()
.filter(|id| live.pin_count(*id) == 0).collect();
if cand.is_empty() { continue; }
let id = cand[pick(cand.len())];
if live.pin(id).is_err() { continue; } let seq = seq_of[&id].clone();
rows.push(snapshot(&live, &seq_of, "pin", &seq, 0, 0, &[], false));
}
8 => { let cand: Vec<SealedId> = live_ids.iter().copied()
.filter(|id| live.pin_count(*id) > 0).collect();
if cand.is_empty() { continue; }
let id = cand[pick(cand.len())];
live.unpin(id).unwrap();
let seq = seq_of[&id].clone();
rows.push(snapshot(&live, &seq_of, "unpin", &seq, 0, 0, &[], false));
}
_ => { if live_ids.is_empty() { continue; }
let id = live_ids[pick(live_ids.len())];
let seq = seq_of[&id].clone();
live.remove(id).unwrap();
rows.push(snapshot(&live, &seq_of, "remove", &seq, 0, 0, &[], false));
}
}
mutating += 1;
}
assert_eq!(mutating, 40, "the walk took its wandering steps");
let m = live.deepest_start(&req).unwrap();
rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));
let body = format!(
"------------------------- MODULE PrefixTreeTraceData -------------------------\n\
\\* Generated by prefix::tests::prefix_trace_dump (specs/run_tlc.zsh runs it).\n\
\\* Do not edit; the generator is the code under test.\n\
EXTENDS PrefixTree\n\nTrace == <<\n{}\n>>\n\n=============================================================================\n",
rows.join(",\n"));
std::fs::write(&out, body).unwrap();
}
#[test]
fn entry_handles_come_back_as_johnnys_entries() {
let full = BlockEntry::new(Slot::new(3).unwrap(), 1, 4096, BlockKind::Full, 2);
let win = BlockEntry::new(Slot::new(5).unwrap(), 2, 8192, BlockKind::Window, 2);
let full2 = BlockEntry::new(Slot::new(4).unwrap(), 1, 4096, BlockKind::Full, 2);
let ha = BlockHandles::new(full, Some(win));
let hb = BlockHandles::new(full2, None);
let mut t: EntryTree = PrefixTree::new();
let a = t.insert(None, 0, &block(1), ha).unwrap();
let b = t.insert(Some(a), BLOCK, &block(2), hb).unwrap();
t.retain_start(b).unwrap();
let m = t.deepest_start(&[block(1), block(2), block(3)].concat());
assert_eq!(m.at, 2 * BLOCK);
assert_eq!(m.blocks, vec![ha, hb]);
assert_eq!(m.blocks[0].full().kind(), BlockKind::Full);
assert_eq!(m.blocks[0].full().offset(), 4096);
assert_eq!(m.blocks[0].full().slot().get(), 3);
assert_eq!(m.blocks[0].window(), Some(win), "the Window entry rides on the same node");
assert_eq!(m.blocks[0].window().unwrap().generation(), 2);
assert_eq!(m.blocks[1].window(), None);
}
}