use std::collections::{BTreeMap, BTreeSet};
use proptest::prelude::*;
use proptest::test_runner::Config;
use relate_core::{NodeId, RelId, Value};
use super::super::Graph;
fn config() -> Config {
Config::default()
}
const NODE_POOL: usize = 6;
const TYPES: [&str; 3] = ["TA", "TB", "TC"];
type ModelHop = (Option<i64>, RelId);
type ModelChunks = Vec<(u32, Vec<ModelHop>)>;
#[derive(Debug, Default)]
struct ModelAdj {
adj: BTreeMap<(NodeId, bool), ModelChunks>,
dead: BTreeSet<RelId>,
}
fn cmp_model_hop(a: &ModelHop, b: &ModelHop) -> std::cmp::Ordering {
match (a.0, b.0) {
(None, None) => b.1.cmp(&a.1),
(None, Some(_)) => std::cmp::Ordering::Less,
(Some(_), None) => std::cmp::Ordering::Greater,
(Some(ta), Some(tb)) => tb.cmp(&ta).then(b.1.cmp(&a.1)),
}
}
fn model_insert_hop(hops: &mut Vec<ModelHop>, hop: ModelHop) {
if let Err(pos) = hops.binary_search_by(|h| cmp_model_hop(h, &hop)) {
hops.insert(pos, hop);
}
}
impl ModelAdj {
fn insert(&mut self, node: NodeId, out: bool, type_id: u32, id: RelId, ts: Option<i64>) {
let chunks = self.adj.entry((node, out)).or_default();
match chunks.iter_mut().find(|(t, _)| *t == type_id) {
Some((_, hops)) => model_insert_hop(hops, (ts, id)),
None => chunks.push((type_id, vec![(ts, id)])),
}
}
fn reposition(&mut self, node: NodeId, out: bool, type_id: u32, id: RelId, ts: Option<i64>) {
let chunks = self.adj.entry((node, out)).or_default();
let unchanged = chunks
.iter()
.any(|(t, hops)| *t == type_id && hops.iter().any(|h| h.1 == id && h.0 == ts));
if unchanged {
return;
}
if let Some(ci) = chunks.iter().position(|(t, _)| *t == type_id) {
let emptied = {
let hops = &mut chunks[ci].1;
if let Some(i) = hops.iter().position(|h| h.1 == id) {
hops.remove(i);
}
hops.is_empty()
};
if emptied {
chunks.remove(ci);
}
}
match chunks.iter_mut().find(|(t, _)| *t == type_id) {
Some((_, hops)) => model_insert_hop(hops, (ts, id)),
None => chunks.push((type_id, vec![(ts, id)])),
}
}
fn delete(&mut self, id: RelId) {
self.dead.insert(id);
}
fn observable(&self, node: NodeId, out: bool) -> ModelChunks {
self.adj
.get(&(node, out))
.map(|chunks| {
chunks
.iter()
.map(|(t, hops)| {
let hops: Vec<ModelHop> = hops
.iter()
.copied()
.filter(|h| !self.dead.contains(&h.1))
.collect();
(*t, hops)
})
.filter(|(_, hops)| !hops.is_empty())
.collect()
})
.unwrap_or_default()
}
}
#[derive(Clone, Debug)]
enum AdjOp {
Create {
start: usize,
end: usize,
ty: usize,
ts: Option<i64>,
},
SetTs { slot: u16, ts: Option<i64> },
Delete { slot: u16 },
}
fn ts_strategy() -> impl Strategy<Value = Option<i64>> {
prop_oneof![
2 => Just(None),
6 => (0i64..64).prop_map(Some),
1 => prop_oneof![Just(i64::MIN), Just(i64::MAX), Just(0i64)].prop_map(Some),
]
}
fn adj_op_strategy() -> impl Strategy<Value = AdjOp> {
prop_oneof![
5 => (
0..NODE_POOL,
0..NODE_POOL,
0..TYPES.len(),
ts_strategy()
)
.prop_map(|(start, end, ty, ts)| AdjOp::Create { start, end, ty, ts }),
3 => (any::<u16>(), ts_strategy())
.prop_map(|(slot, ts)| AdjOp::SetTs { slot, ts }),
2 => any::<u16>().prop_map(|slot| AdjOp::Delete { slot }),
]
}
fn observable(g: &Graph, node: NodeId, out: bool) -> ModelChunks {
let side = if out { g.out_side() } else { g.in_side() };
let Some(adj) = side.delta().get(&node) else {
return Vec::new();
};
let region = side.sealed().region(node);
let ts = g.commit_ts();
adj.chunks
.iter()
.map(|chunk| {
let mut hops = Vec::new();
adj.for_each_hop_of(region, chunk.type_id, ts, |hop| hops.push((hop.ts, hop.id)));
let hops: Vec<ModelHop> = hops
.into_iter()
.filter(|(_, id)| g.rel_exists(*id))
.collect();
(chunk.type_id, hops)
})
.filter(|(_, hops)| !hops.is_empty())
.collect()
}
fn assert_observed_eq(
g: &Graph,
model: &ModelAdj,
nodes: &[NodeId],
normalise: impl Fn(ModelChunks) -> ModelChunks,
) {
for &node in nodes {
for out in [true, false] {
let real = normalise(observable(g, node, out));
let expected = normalise(model.observable(node, out));
assert_eq!(
real, expected,
"adjacency divergence for node {node} (out={out})"
);
}
}
}
fn apply_op(
g: &Graph,
model: &mut ModelAdj,
nodes: &[NodeId],
live: &mut Vec<RelId>,
type_ids: &[u32],
op: &AdjOp,
) {
match *op {
AdjOp::Create { start, end, ty, ts } => {
let mut props = BTreeMap::new();
if let Some(t) = ts {
props.insert("ts".to_string(), Value::Int(t));
}
g.begin_write().unwrap();
let id = g
.create_rel(nodes[start], nodes[end], TYPES[ty].to_string(), props)
.unwrap();
g.commit_write();
model.insert(nodes[start], true, type_ids[ty], id, ts);
model.insert(nodes[end], false, type_ids[ty], id, ts);
live.push(id);
}
AdjOp::SetTs { slot, ts } => {
if live.is_empty() {
return;
}
live.sort_unstable();
let id = live[(slot as usize) % live.len()];
let (start, end, type_id) = {
let rel = g.rel(id).expect("live relationship materializes");
(
rel.start,
rel.end,
g.interner.get_id(&rel.rel_type).unwrap(),
)
};
let value = match ts {
Some(t) => Value::Int(t),
None => Value::Null,
};
g.begin_write().unwrap();
g.set_property_rel(id, "ts", value);
g.commit_write();
model.reposition(start, true, type_id, id, ts);
model.reposition(end, false, type_id, id, ts);
}
AdjOp::Delete { slot } => {
if live.is_empty() {
return;
}
live.sort_unstable();
let idx = (slot as usize) % live.len();
let id = live.remove(idx);
g.begin_write().unwrap();
g.delete_rel(id);
g.commit_write();
model.delete(id);
}
}
}
fn graph_fixture() -> (Graph, Vec<NodeId>, Vec<u32>) {
let g = Graph::default();
let mut nodes = Vec::with_capacity(NODE_POOL);
g.begin_write().unwrap();
for _ in 0..NODE_POOL {
nodes.push(g.create_node(vec!["N".into()], BTreeMap::new()).unwrap());
}
g.commit_write();
let type_ids: Vec<u32> = TYPES.iter().map(|t| g.interner.intern(t)).collect();
(g, nodes, type_ids)
}
proptest! {
#![proptest_config(config())]
#[test]
fn adjacency_matches_reference_model(ops in prop::collection::vec(adj_op_strategy(), 0..=200)) {
let (g, nodes, type_ids) = graph_fixture();
let mut model = ModelAdj::default();
let mut live: Vec<RelId> = Vec::new();
for op in &ops {
apply_op(&g, &mut model, &nodes, &mut live, &type_ids, op);
assert_observed_eq(&g, &model, &nodes, |chunks| chunks);
}
}
#[test]
fn adjacency_model_proptest_compaction_confluence(
steps in prop::collection::vec((adj_op_strategy(), any::<bool>()), 0..=200)
) {
let (g, nodes, type_ids) = graph_fixture();
let mut model = ModelAdj::default();
let mut live: Vec<RelId> = Vec::new();
for (op, fold) in &steps {
apply_op(&g, &mut model, &nodes, &mut live, &type_ids, op);
if *fold {
g.compact_adjacency_at_watermark(u64::MAX);
g.compact_adjacency_at_watermark(u64::MAX);
}
assert_observed_eq(&g, &model, &nodes, |mut chunks| {
chunks.sort_by_key(|(type_id, _)| *type_id);
chunks
});
}
}
}
#[test]
#[ignore = "needs hop-level xmin versioning (a repositioned delta hop is visible to older snapshots)"]
fn adjacency_model_proptest_snapshot_freeze() {}
#[test]
fn add_then_delete_nets_nothing() {
let g = Graph::default();
let (a, b) = crate::graph::test_support::endpoints(&g);
g.begin_write().unwrap();
let r = g
.create_rel(
a,
b,
"T".into(),
BTreeMap::from([("ts".into(), Value::Int(7))]),
)
.unwrap();
g.commit_write();
assert_eq!(observable(&g, a, true).len(), 1);
g.begin_write().unwrap();
g.delete_rel(r);
g.commit_write();
assert!(observable(&g, a, true).is_empty());
assert!(observable(&g, b, false).is_empty());
}
#[test]
fn ts_update_of_only_hop() {
let g = Graph::default();
let (a, b) = crate::graph::test_support::endpoints(&g);
g.begin_write().unwrap();
let r = g
.create_rel(
a,
b,
"T".into(),
BTreeMap::from([("ts".into(), Value::Int(1))]),
)
.unwrap();
g.commit_write();
g.begin_write().unwrap();
g.set_property_rel(r, "ts", Value::Int(9));
g.commit_write();
assert_eq!(
observable(&g, a, true),
vec![(g.interner.get_id("T").unwrap(), vec![(Some(9), r)])]
);
g.begin_write().unwrap();
g.set_property_rel(r, "ts", Value::Null);
g.commit_write();
assert_eq!(
observable(&g, a, true),
vec![(g.interner.get_id("T").unwrap(), vec![(None, r)])]
);
}
#[test]
fn equal_ts_ties_newest_first_and_missing_ts_first() {
let g = Graph::default();
let (a, b) = crate::graph::test_support::endpoints(&g);
let mut ids = Vec::new();
g.begin_write().unwrap();
for _ in 0..3 {
ids.push(
g.create_rel(
a,
b,
"T".into(),
BTreeMap::from([("ts".into(), Value::Int(5))]),
)
.unwrap(),
);
}
ids.push(g.create_rel(a, b, "T".into(), BTreeMap::new()).unwrap());
g.commit_write();
let tid = g.interner.get_id("T").unwrap();
let hops = &observable(&g, a, true)[0];
assert_eq!(hops.0, tid);
assert_eq!(
hops.1,
vec![
(None, ids[3]),
(Some(5), ids[2]),
(Some(5), ids[1]),
(Some(5), ids[0])
]
);
}
#[test]
fn multiple_type_chunks_iterate_in_first_seen_order() {
let g = Graph::default();
let (a, b) = crate::graph::test_support::endpoints(&g);
g.begin_write().unwrap();
let r1 = g
.create_rel(
a,
b,
"TB".into(),
BTreeMap::from([("ts".into(), Value::Int(1))]),
)
.unwrap();
let r2 = g
.create_rel(
a,
b,
"TA".into(),
BTreeMap::from([("ts".into(), Value::Int(2))]),
)
.unwrap();
let r3 = g
.create_rel(
a,
b,
"TB".into(),
BTreeMap::from([("ts".into(), Value::Int(3))]),
)
.unwrap();
g.commit_write();
let ta = g.interner.get_id("TA").unwrap();
let tb = g.interner.get_id("TB").unwrap();
assert_eq!(
observable(&g, a, true),
vec![
(tb, vec![(Some(3), r3), (Some(1), r1)]),
(ta, vec![(Some(2), r2)])
]
);
}
#[test]
fn delete_everything_leaves_empty_observable_adjacency() {
let g = Graph::default();
let (a, b) = crate::graph::test_support::endpoints(&g);
let mut ids = Vec::new();
g.begin_write().unwrap();
for (i, ty) in ["TA", "TB", "TC", "TA"].iter().enumerate() {
let props = if i % 2 == 0 {
BTreeMap::from([("ts".into(), Value::Int(i as i64))])
} else {
BTreeMap::new()
};
ids.push(g.create_rel(a, b, (*ty).into(), props).unwrap());
}
g.commit_write();
for id in ids {
g.begin_write().unwrap();
g.delete_rel(id);
g.commit_write();
}
for node in [a, b] {
assert!(observable(&g, node, true).is_empty());
assert!(observable(&g, node, false).is_empty());
}
}