use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex, RwLock};
use relate_core::{NodeId, Value};
use super::access::visible_version;
#[cfg(feature = "test-hooks")]
use super::build_counter::SharedCounter;
use super::Graph;
use crate::vector_similarity::{value_coord, value_coords};
#[cfg(feature = "test-hooks")]
static SERVED: SharedCounter = SharedCounter::new();
#[cfg(feature = "test-hooks")]
#[doc(hidden)]
pub fn take_vector_matrix_serves(label: &str) -> u64 {
SERVED.take(label)
}
#[cfg(feature = "test-hooks")]
fn note_served(label: &str) {
SERVED.bump(label);
}
#[cfg(not(feature = "test-hooks"))]
fn note_served(_label: &str) {}
#[derive(Debug, Default)]
pub(super) struct VectorMatrixSlot {
dirty: Mutex<HashMap<NodeId, (u64, u64)>>,
matrix: RwLock<Option<VectorMatrix>>,
}
impl VectorMatrixSlot {
fn has_pending_at(&self, ts: u64) -> bool {
self.dirty
.lock()
.expect("vector matrix dirty lock poisoned")
.values()
.any(|&(oldest, _)| oldest <= ts)
}
fn serves_reader(&self, m: &VectorMatrix, dim: usize, ts: u64) -> bool {
m.serves(dim, ts) && !self.has_pending_at(ts)
}
fn take_pending_at(&self, ts: u64) -> Vec<NodeId> {
let mut dirty = self
.dirty
.lock()
.expect("vector matrix dirty lock poisoned");
let mut taken = Vec::new();
dirty.retain(|&id, (oldest, newest)| {
if *oldest > ts {
return true;
}
taken.push(id);
if *newest > ts {
*oldest = ts + 1;
return true;
}
false
});
taken
}
fn note_write(&self, id: NodeId, ts: u64) {
let mut dirty = self
.dirty
.lock()
.expect("vector matrix dirty lock poisoned");
let entry = dirty.entry(id).or_insert((ts, ts));
entry.0 = entry.0.min(ts);
entry.1 = entry.1.max(ts);
}
}
enum Packed {
Row(Vec<f32>),
Skip,
Inexact,
}
#[derive(Debug)]
pub(crate) struct VectorMatrix {
dim: usize,
built_ts: u64,
ids: Vec<NodeId>,
rows: Vec<f32>,
pos: HashMap<NodeId, usize>,
inexact: HashSet<NodeId>,
}
impl VectorMatrix {
fn new(dim: usize, built_ts: u64) -> Self {
Self {
dim,
built_ts,
ids: Vec::new(),
rows: Vec::new(),
pos: HashMap::new(),
inexact: HashSet::new(),
}
}
pub(crate) fn rows(&self) -> impl Iterator<Item = (NodeId, &[f32])> + '_ {
self.ids
.iter()
.copied()
.zip(self.rows.chunks_exact(self.dim))
}
fn apply(&mut self, id: NodeId, packed: Packed) {
match packed {
Packed::Row(row) => {
self.inexact.remove(&id);
match self.pos.get(&id) {
Some(&at) => {
self.rows[at * self.dim..(at + 1) * self.dim].copy_from_slice(&row)
}
None => {
self.pos.insert(id, self.ids.len());
self.ids.push(id);
self.rows.extend_from_slice(&row);
}
}
}
Packed::Skip => {
self.inexact.remove(&id);
self.remove(id);
}
Packed::Inexact => {
self.remove(id);
self.inexact.insert(id);
}
}
}
fn remove(&mut self, id: NodeId) {
let Some(at) = self.pos.remove(&id) else {
return;
};
let last = self.ids.len() - 1;
if at != last {
let moved = self.ids[last];
self.ids[at] = moved;
self.rows
.copy_within(last * self.dim..(last + 1) * self.dim, at * self.dim);
self.pos.insert(moved, at);
}
self.ids.pop();
self.rows.truncate(last * self.dim);
}
fn can_refresh(&self, dim: usize, ts: u64) -> bool {
self.dim == dim && self.built_ts <= ts
}
fn serves(&self, dim: usize, ts: u64) -> bool {
self.can_refresh(dim, ts) && self.inexact.is_empty()
}
}
fn pack_value(value: &Value, dim: usize) -> Packed {
let Some(coords) = value_coords(value) else {
return Packed::Skip;
};
if coords.len() != dim {
return Packed::Skip;
}
let mut row = Vec::with_capacity(dim);
let mut exact = true;
for coord in coords.iter() {
let Some(c) = value_coord(coord) else {
return Packed::Skip;
};
let narrowed = c as f32;
exact &= f64::from(narrowed) == c;
row.push(narrowed);
}
if exact {
Packed::Row(row)
} else {
Packed::Inexact
}
}
impl Graph {
pub(super) fn vector_matrix_note_write(&self, labels: &[u32], id: NodeId) {
if self.indexes.vector_matrices.is_empty() {
return;
}
let ts = self.read_ts();
for entry in self.indexes.vector_matrices.iter() {
if labels.contains(&entry.key().0) {
entry.value().note_write(id, ts);
}
}
}
fn pack_node(&self, id: NodeId, lid: u32, kid: u32, ts: u64, dim: usize) -> Packed {
let Some(versions) = self.nodes.get(&id) else {
return Packed::Skip;
};
let Some(version) = visible_version(&versions, ts) else {
return Packed::Skip;
};
let live = &version.live;
if !live.labels.contains(&lid) {
return Packed::Skip;
}
match live.props.get(kid) {
Some(value) => pack_value(value, dim),
None => Packed::Skip,
}
}
pub(crate) fn with_vector_matrix<R>(
&self,
label: &str,
key: &str,
ts: u64,
dim: usize,
scan: impl FnOnce(&VectorMatrix) -> R,
) -> Option<R> {
let lid = self.label_id(label)?;
let kid = self.prop_key_id(key)?;
let slot: Arc<VectorMatrixSlot> =
Arc::clone(&self.indexes.vector_matrices.entry((lid, kid)).or_default());
{
let matrix = slot.matrix.read().expect("vector matrix lock poisoned");
if let Some(m) = matrix.as_ref() {
if slot.serves_reader(m, dim, ts) {
note_served(label);
return Some(scan(m));
}
}
}
{
let mut matrix = slot.matrix.write().expect("vector matrix lock poisoned");
match matrix.as_mut() {
Some(m) if !m.can_refresh(dim, ts) => return None,
Some(m) => {
for id in slot.take_pending_at(ts) {
let packed = self.pack_node(id, lid, kid, ts, dim);
m.apply(id, packed);
}
m.built_ts = ts;
}
None => {
if self.read_ts() > ts {
return None;
}
let mut m = VectorMatrix::new(dim, ts);
for id in self.node_ids_with_label_at(label, ts) {
let packed = self.pack_node(id, lid, kid, ts, dim);
m.apply(id, packed);
}
slot.take_pending_at(ts);
*matrix = Some(m);
}
}
}
let matrix = slot.matrix.read().expect("vector matrix lock poisoned");
let m = matrix.as_ref()?;
if !slot.serves_reader(m, dim, ts) {
return None;
}
note_served(label);
Some(scan(m))
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
fn floats(xs: &[f64]) -> Value {
Value::List(Arc::new(xs.iter().map(|&x| Value::Float(x)).collect()))
}
#[test]
fn pack_value_mirrors_the_value_scans_skip_and_exactness_rules() {
assert!(
matches!(pack_value(&floats(&[1.0, 0.5]), 2), Packed::Row(r) if r == vec![1.0, 0.5])
);
assert!(
matches!(pack_value(&floats(&[1.0]), 2), Packed::Skip),
"wrong length"
);
assert!(
matches!(pack_value(&floats(&[f64::NAN, 1.0]), 2), Packed::Skip),
"non-finite"
);
assert!(
matches!(pack_value(&Value::Int(3), 1), Packed::Skip),
"scalar"
);
assert!(
matches!(pack_value(&floats(&[0.1, 1.0]), 2), Packed::Inexact),
"0.1 is not f32-exact"
);
let ints = Value::List(Arc::new(vec![Value::Int(3), Value::Int(1 << 30)]));
assert!(
matches!(pack_value(&ints, 2), Packed::Row(_)),
"2^30 is f32-exact"
);
let big = Value::List(Arc::new(vec![Value::Int((1 << 30) + 1)]));
assert!(
matches!(pack_value(&big, 1), Packed::Inexact),
"2^30+1 is not"
);
}
#[test]
fn apply_keeps_rows_dense_across_updates_and_removals() {
let mut m = VectorMatrix::new(2, 1);
for id in 1..=4 {
m.apply(id, Packed::Row(vec![id as f32, 0.0]));
}
m.apply(2, Packed::Skip);
m.apply(3, Packed::Row(vec![30.0, 1.0]));
m.apply(1, Packed::Inexact);
let mut rows: Vec<(NodeId, Vec<f32>)> = m.rows().map(|(id, r)| (id, r.to_vec())).collect();
rows.sort_by_key(|(id, _)| *id);
assert_eq!(rows, vec![(3, vec![30.0, 1.0]), (4, vec![4.0, 0.0])]);
assert!(!m.serves(2, 1), "an inexact carrier blocks the matrix");
m.apply(1, Packed::Skip);
assert!(m.serves(2, 1));
assert!(!m.serves(3, 1), "another dimension");
assert!(!m.serves(2, 0), "an older snapshot");
}
#[test]
fn dirty_entries_drain_only_up_to_the_readers_snapshot() {
let slot = VectorMatrixSlot::default();
slot.note_write(7, 5);
slot.note_write(7, 9);
slot.note_write(8, 12);
assert!(!slot.has_pending_at(4));
assert!(slot.has_pending_at(5));
assert_eq!(slot.take_pending_at(6), vec![7]);
assert!(slot.has_pending_at(7));
let mut later = slot.take_pending_at(12);
later.sort_unstable();
assert_eq!(later, vec![7, 8]);
assert!(!slot.has_pending_at(u64::MAX));
}
}