#[cfg(test)]
use std::cell::Cell;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex, MutexGuard};
use relate_core::{NodeId, RelId};
use relate_ir::RelPattern;
use crate::store::{LiveNode, RelTypes};
use super::{visible, visible_version, Graph};
#[cfg(test)]
thread_local! {
static LABEL_PROBE_CHECKS: Cell<u64> = const { Cell::new(0) };
}
#[cfg(test)]
pub(crate) fn take_label_probe_checks() -> u64 {
LABEL_PROBE_CHECKS.with(|c| c.replace(0))
}
#[cfg(test)]
fn count_label_probe_check() {
LABEL_PROBE_CHECKS.with(|c| c.set(c.get() + 1));
}
#[cfg(not(test))]
fn count_label_probe_check() {}
const FIRST_COPY: usize = 64;
struct LabelMemo {
checked: HashSet<NodeId>,
pending: VecDeque<NodeId>,
visible: i64,
whole: bool,
next_copy: usize,
}
impl LabelMemo {
fn new() -> Self {
Self {
checked: HashSet::new(),
pending: VecDeque::new(),
visible: 0,
whole: false,
next_copy: FIRST_COPY,
}
}
}
#[derive(Clone)]
pub(crate) struct LabelProbe {
snapshot_ts: u64,
memos: Arc<Mutex<HashMap<u32, LabelMemo>>>,
}
impl LabelProbe {
pub(crate) fn new(snapshot_ts: u64) -> Self {
Self {
snapshot_ts,
memos: Arc::default(),
}
}
fn memos(&self) -> MutexGuard<'_, HashMap<u32, LabelMemo>> {
self.memos.lock().unwrap_or_else(|poisoned| {
let mut memos = poisoned.into_inner();
memos.clear();
self.memos.clear_poison();
memos
})
}
pub(crate) fn carriers_below(&self, graph: &Graph, label: &str, k: i64) -> Option<i64> {
let Some(lid) = graph.label_id(label) else {
return (k > 0).then_some(0);
};
let mut memos = self.memos();
let memo = memos.entry(lid).or_insert_with(LabelMemo::new);
loop {
if memo.visible >= k {
return None;
}
if let Some(id) = memo.pending.pop_front() {
memo.checked.insert(id);
count_label_probe_check();
if graph.node_carries_label_at(id, lid, self.snapshot_ts) {
memo.visible += 1;
}
} else if memo.whole {
return Some(memo.visible);
} else {
let (ids, whole) = graph.label_index_copy(lid, memo.next_copy);
memo.next_copy = memo.next_copy.saturating_mul(2);
memo.whole = whole;
memo.pending = ids
.into_iter()
.filter(|id| !memo.checked.contains(id))
.collect();
}
}
}
}
impl Graph {
pub(crate) fn label_id(&self, label: &str) -> Option<u32> {
self.interner.get_id(label)
}
pub(crate) fn prop_key_id(&self, key: &str) -> Option<u32> {
self.interner.get_id(key)
}
pub(crate) fn rel_type_id(&self, rel_type: &str) -> Option<u32> {
self.interner.get_id(rel_type)
}
pub(crate) fn rel_types<T: AsRef<str>>(&self, names: &[T]) -> RelTypes {
RelTypes::resolve(&self.interner, names)
}
pub(crate) fn rel_types_of(&self, rel: &RelPattern) -> RelTypes {
RelTypes::of_pattern(&self.interner, rel)
}
pub(crate) fn rel_type_name(&self, tid: u32) -> Arc<str> {
self.interner.get(tid)
}
pub(crate) fn rel_type_name_shared(&self, id: RelId, ts: u64) -> Option<Arc<str>> {
self.rels
.get(&id)
.and_then(|vers| visible_version(&vers, ts).map(|ver| ver.live.type_name_shared()))
}
pub(super) fn label_index_copy(&self, lid: u32, cap: usize) -> (Vec<NodeId>, bool) {
match self.indexes.label_index.get(&lid) {
Some(set) => (set.iter().take(cap).copied().collect(), set.len() <= cap),
None => (Vec::new(), true),
}
}
pub(crate) fn with_visible_node<R>(
&self,
id: NodeId,
ts: u64,
f: impl FnOnce(&LiveNode) -> R,
) -> Option<R> {
self.nodes.get(&id).and_then(|vers| {
vers.iter()
.rev()
.find(|v| visible(v.xmin, v.xmax, ts))
.map(|v| f(v.live))
})
}
pub(super) fn node_carries_label_at(&self, id: NodeId, lid: u32, ts: u64) -> bool {
self.with_visible_node(id, ts, |live| live.has_label(lid))
.unwrap_or(false)
}
pub(crate) fn interned_label_id(&self, label: &str) -> Option<u32> {
self.label_id(label)
}
pub(crate) fn node_has_label_id_at(&self, id: NodeId, ts: u64, lid: u32) -> Option<bool> {
self.with_visible_node(id, ts, |live| live.has_label(lid))
}
pub(crate) fn node_ids_with_label_at(&self, label: &str, ts: u64) -> Vec<NodeId> {
let Some(lid) = self.label_id(label) else {
return Vec::new();
};
let candidates: Vec<NodeId> = match self.indexes.label_index.get(&lid) {
Some(set) => set.iter().copied().collect(),
None => return Vec::new(),
};
let mut ids: Vec<_> = candidates
.into_iter()
.filter(|&id| self.node_carries_label_at(id, lid, ts))
.collect();
ids.sort_unstable();
ids
}
pub(crate) fn rel_ids_of_type_at(&self, rel_type: &str, ts: u64) -> Vec<RelId> {
let Some(type_id) = self.rel_type_id(rel_type) else {
return Vec::new();
};
let mut ids = Vec::new();
self.rels.for_each(|id, vers| {
let matches = vers
.iter()
.rev()
.find(|v| visible(v.xmin, v.xmax, ts))
.is_some_and(|v| v.live.type_id == type_id);
if matches {
ids.push(id);
}
});
ids.sort_unstable();
ids
}
}
#[cfg(test)]
mod tests;