SourceQuery gains `front` (serde default false, so an old client's request decodes as before). The one owner of the list is sources::FRONT_PAGE_FILES; the Qdrant filter matches `path` against it with MatchAny on the existing keyword index, composed with the `repo` condition. The CLI prints the citation line range as before. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
393 lines
15 KiB
Rust
393 lines
15 KiB
Rust
//! In-memory ports for the projector's tests. Each fake is a handle on shared
|
|
//! state, so a test keeps observing after it has moved the fake into a
|
|
//! projector or a worker thread.
|
|
|
|
use std::collections::{BTreeMap, BTreeSet};
|
|
use std::sync::{Arc, Condvar, Mutex};
|
|
use std::time::Duration;
|
|
|
|
use anyhow::{Result, bail, ensure};
|
|
|
|
use crate::sources::{DescribedSources, SourceIndex, SourcePoint, SourceRow, SourcesMeta};
|
|
|
|
use super::{CollectionMeta, Described, Embedder, Hit, ModelIdentity, Point, VectorIndex, point_id};
|
|
|
|
pub(crate) fn identity(digest: &str) -> ModelIdentity {
|
|
ModelIdentity { name: "model".into(), digest: digest.into(), dimensions: 4 }
|
|
}
|
|
|
|
/// A door a test holds shut: `embed` announces it has arrived and waits.
|
|
#[derive(Clone, Default)]
|
|
pub(crate) struct Gate(Arc<(Mutex<(u32, bool)>, Condvar)>);
|
|
|
|
impl Gate {
|
|
pub(crate) fn shut() -> Self {
|
|
Self::default()
|
|
}
|
|
|
|
/// Blocks until `count` calls to `embed` have arrived at the gate.
|
|
pub(crate) fn wait_arrived(&self, count: u32) {
|
|
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
|
let mut state = self.0.0.lock().unwrap();
|
|
while state.0 < count {
|
|
let left = deadline.saturating_duration_since(std::time::Instant::now());
|
|
assert!(!left.is_zero(), "{count} calls never arrived at the gate; {} did", state.0);
|
|
state = self.0.1.wait_timeout(state, left).unwrap().0;
|
|
}
|
|
}
|
|
|
|
/// Shuts the door again and forgets who arrived, so a test that let start-up
|
|
/// work through can hold the next call.
|
|
pub(crate) fn shut_again(&self) {
|
|
let mut state = self.0.0.lock().unwrap();
|
|
*state = (0, false);
|
|
}
|
|
|
|
pub(crate) fn open(&self) {
|
|
self.0.0.lock().unwrap().1 = true;
|
|
self.0.1.notify_all();
|
|
}
|
|
|
|
fn pass(&self) {
|
|
let mut state = self.0.0.lock().unwrap();
|
|
state.0 += 1;
|
|
self.0.1.notify_all();
|
|
while !state.1 {
|
|
state = self.0.1.wait(state).unwrap();
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) struct EmbedderState {
|
|
pub(crate) identity: ModelIdentity,
|
|
pub(crate) down: bool,
|
|
/// Whether embedding fails while the identity read still answers.
|
|
pub(crate) embed_fails: bool,
|
|
/// The texts of every completed call, in order.
|
|
pub(crate) embedded: Vec<Vec<String>>,
|
|
/// The bound each completed call was given, in order.
|
|
pub(crate) bounds: Vec<Duration>,
|
|
/// The length of the vectors it answers with, where that is not the
|
|
/// identity's.
|
|
pub(crate) vector_length: Option<usize>,
|
|
/// The bound each identity read was given, in order.
|
|
pub(crate) identity_bounds: Vec<Duration>,
|
|
/// Whether an identity read is never answered: it fails when its bound
|
|
/// has passed, as an adapter that honours its bound does.
|
|
pub(crate) hang_identity: bool,
|
|
/// How long an identity read takes to answer, when it answers.
|
|
pub(crate) identity_delay: Duration,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub(crate) struct FakeEmbedder {
|
|
pub(crate) state: Arc<Mutex<EmbedderState>>,
|
|
gate: Option<Gate>,
|
|
}
|
|
|
|
impl FakeEmbedder {
|
|
pub(crate) fn new(digest: &str) -> Self {
|
|
let state = EmbedderState { identity: identity(digest), down: false, embed_fails: false, embedded: Vec::new(), bounds: Vec::new(), vector_length: None, identity_bounds: Vec::new(), hang_identity: false, identity_delay: Duration::ZERO };
|
|
Self { state: Arc::new(Mutex::new(state)), gate: None }
|
|
}
|
|
|
|
pub(crate) fn behind(mut self, gate: &Gate) -> Self {
|
|
self.gate = Some(gate.clone());
|
|
self
|
|
}
|
|
|
|
pub(crate) fn texts(&self) -> Vec<String> {
|
|
self.state.lock().unwrap().embedded.iter().flatten().cloned().collect()
|
|
}
|
|
}
|
|
|
|
impl Embedder for FakeEmbedder {
|
|
fn model_identity(&mut self, within: Duration) -> Result<ModelIdentity> {
|
|
let mut state = self.state.lock().unwrap();
|
|
state.identity_bounds.push(within);
|
|
if state.hang_identity {
|
|
drop(state);
|
|
std::thread::sleep(within);
|
|
bail!("the embedder did not answer within {within:?}");
|
|
}
|
|
if state.down {
|
|
bail!("the embedder is down");
|
|
}
|
|
let (identity, delay) = (state.identity.clone(), state.identity_delay);
|
|
drop(state);
|
|
std::thread::sleep(delay);
|
|
Ok(identity)
|
|
}
|
|
|
|
fn embed(&mut self, texts: &[String], within: Duration) -> Result<Vec<Vec<f32>>> {
|
|
if let Some(gate) = &self.gate {
|
|
gate.pass();
|
|
}
|
|
let mut state = self.state.lock().unwrap();
|
|
if state.down || state.embed_fails {
|
|
bail!("the embedder is down");
|
|
}
|
|
state.embedded.push(texts.to_vec());
|
|
state.bounds.push(within);
|
|
let dimensions = state.vector_length.unwrap_or(state.identity.dimensions as usize);
|
|
Ok(texts.iter().map(|text| (0..dimensions).map(|at| (text.len() + at) as f32).collect()).collect())
|
|
}
|
|
}
|
|
|
|
pub(crate) struct Stored {
|
|
pub(crate) label: Described,
|
|
pub(crate) points: BTreeMap<String, Point>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub(crate) struct IndexState {
|
|
pub(crate) collections: BTreeMap<String, Stored>,
|
|
pub(crate) down: bool,
|
|
pub(crate) recreated: Vec<(String, CollectionMeta)>,
|
|
/// The point ids of every upsert call, in order.
|
|
pub(crate) upserts: Vec<Vec<String>>,
|
|
/// What every search answers, whatever the vector: the test decides the
|
|
/// candidates, as a real index would decide them from vectors.
|
|
pub(crate) hits: Vec<Hit>,
|
|
/// The collection, vector length and limit of every search, in order.
|
|
pub(crate) searches: Vec<(String, usize, u32)>,
|
|
/// The point ids each search was restricted to, in order.
|
|
pub(crate) among: Vec<Vec<String>>,
|
|
/// How many times every point id was listed: only a reconciliation does.
|
|
pub(crate) listed: u32,
|
|
/// Whether a search fails at the vector store, the rest of it working.
|
|
pub(crate) fail_search: bool,
|
|
/// The bound each describe and each search was given, in order, by call.
|
|
pub(crate) bounds: Vec<(&'static str, Duration)>,
|
|
/// How many points the collection held when each search reached it.
|
|
pub(crate) held_when_searched: Vec<usize>,
|
|
}
|
|
|
|
#[derive(Clone, Default)]
|
|
pub(crate) struct FakeIndex {
|
|
pub(crate) state: Arc<Mutex<IndexState>>,
|
|
/// The source collection, held beside the mind's so one fake serves a
|
|
/// worker that owns both.
|
|
pub(crate) sources: FakeSources,
|
|
}
|
|
|
|
impl FakeIndex {
|
|
pub(crate) fn holding(&self, collection: &str) -> BTreeSet<String> {
|
|
let state = self.state.lock().unwrap();
|
|
state.collections.get(collection).map(|stored| stored.points.keys().cloned().collect()).unwrap_or_default()
|
|
}
|
|
|
|
/// Plants a collection this organ did not make, or made for another mind.
|
|
pub(crate) fn plant(&self, collection: &str, label: Described) {
|
|
self.state.lock().unwrap().collections.insert(collection.into(), Stored { label, points: BTreeMap::new() });
|
|
}
|
|
}
|
|
|
|
impl VectorIndex for FakeIndex {
|
|
fn describe(&mut self, collection: &str, within: Duration) -> Result<Described> {
|
|
let mut state = self.state.lock().unwrap();
|
|
state.bounds.push(("describe", within));
|
|
if state.down {
|
|
bail!("the vector store is down");
|
|
}
|
|
Ok(state.collections.get(collection).map_or(Described::Absent, |stored| stored.label.clone()))
|
|
}
|
|
|
|
fn recreate(&mut self, collection: &str, meta: &CollectionMeta) -> Result<()> {
|
|
let mut state = self.state.lock().unwrap();
|
|
if state.down {
|
|
bail!("the vector store is down");
|
|
}
|
|
state.recreated.push((collection.into(), meta.clone()));
|
|
state
|
|
.collections
|
|
.insert(collection.into(), Stored { label: Described::Labelled(meta.clone()), points: BTreeMap::new() });
|
|
Ok(())
|
|
}
|
|
|
|
fn ids(&mut self, collection: &str) -> Result<BTreeSet<String>> {
|
|
let mut state = self.state.lock().unwrap();
|
|
if state.down {
|
|
bail!("the vector store is down");
|
|
}
|
|
state.listed += 1;
|
|
Ok(state.collections.get(collection).map(|stored| stored.points.keys().cloned().collect()).unwrap_or_default())
|
|
}
|
|
|
|
fn upsert(&mut self, collection: &str, points: &[Point]) -> Result<()> {
|
|
let mut state = self.state.lock().unwrap();
|
|
if state.down {
|
|
bail!("the vector store is down");
|
|
}
|
|
state.upserts.push(points.iter().map(|point| point.id.clone()).collect());
|
|
let Some(stored) = state.collections.get_mut(collection) else { bail!("no collection {collection}") };
|
|
for point in points {
|
|
stored.points.insert(point.id.clone(), point.clone());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn search(&mut self, collection: &str, vector: &[f32], among: &[String], limit: u32, within: Duration) -> Result<Vec<Hit>> {
|
|
let mut state = self.state.lock().unwrap();
|
|
state.bounds.push(("search", within));
|
|
if state.down {
|
|
bail!("the vector store is down");
|
|
}
|
|
state.searches.push((collection.into(), vector.len(), limit));
|
|
state.among.push(among.to_vec());
|
|
ensure!(!state.fail_search, "the vector store failed the search");
|
|
ensure!(state.collections.contains_key(collection), "no collection {collection}");
|
|
let held = state.collections[collection].points.len();
|
|
state.held_when_searched.push(held);
|
|
// A filtered exact index: only the points handed in are scored.
|
|
Ok(state.hits.iter().filter(|hit| among.contains(&point_id(&hit.doc_id))).take(limit as usize).cloned().collect())
|
|
}
|
|
}
|
|
|
|
/// A working embedder and vector store, for tests whose subject is elsewhere.
|
|
pub(crate) fn pair() -> (FakeEmbedder, FakeIndex) {
|
|
(FakeEmbedder::new("d1"), FakeIndex::default())
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub(crate) struct SourcesState {
|
|
pub(crate) described: Option<DescribedSources>,
|
|
pub(crate) points: BTreeMap<String, SourcePoint>,
|
|
/// How many times the collection was recreated.
|
|
pub(crate) recreated: u32,
|
|
pub(crate) upsert_calls: u32,
|
|
/// Every upsert call refuses once this many have succeeded.
|
|
pub(crate) fail_upserts_after: Option<u32>,
|
|
pub(crate) cursor_writes: Vec<std::collections::BTreeMap<String, String>>,
|
|
pub(crate) deletes: Vec<(String, Option<Vec<String>>)>,
|
|
/// A delete naming this repo refuses.
|
|
pub(crate) fail_deletes_of: Option<String>,
|
|
/// The repo filter and limit of every search, in order.
|
|
pub(crate) searches: Vec<(Option<String>, u32)>,
|
|
}
|
|
|
|
/// An in-memory source collection: a brute-force cosine search over what it
|
|
/// holds, so a test sees what a filter and a limit do.
|
|
#[derive(Clone, Default)]
|
|
pub(crate) struct FakeSources {
|
|
pub(crate) state: Arc<Mutex<SourcesState>>,
|
|
}
|
|
|
|
impl FakeSources {
|
|
pub(crate) fn plant(&self, described: DescribedSources) {
|
|
self.state.lock().unwrap().described = Some(described);
|
|
}
|
|
|
|
pub(crate) fn cursors(&self) -> BTreeMap<String, String> {
|
|
match &self.state.lock().unwrap().described {
|
|
Some(DescribedSources::Labelled { cursors, .. }) => cursors.clone(),
|
|
_ => BTreeMap::new(),
|
|
}
|
|
}
|
|
|
|
/// (repo, path, chunk_index, commit) of every point held, sorted.
|
|
pub(crate) fn held(&self) -> Vec<(String, String, u32, String)> {
|
|
let state = self.state.lock().unwrap();
|
|
let mut held: Vec<_> = state
|
|
.points
|
|
.values()
|
|
.map(|point| (point.payload.repo.clone(), point.payload.path.clone(), point.payload.chunk_index, point.payload.commit.clone()))
|
|
.collect();
|
|
held.sort();
|
|
held
|
|
}
|
|
|
|
pub(crate) fn ids(&self) -> BTreeSet<String> {
|
|
self.state.lock().unwrap().points.keys().cloned().collect()
|
|
}
|
|
}
|
|
|
|
fn cosine(a: &[f32], b: &[f32]) -> f32 {
|
|
let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
|
|
let norm = |v: &[f32]| v.iter().map(|x| x * x).sum::<f32>().sqrt();
|
|
dot / (norm(a) * norm(b)).max(f32::MIN_POSITIVE)
|
|
}
|
|
|
|
impl SourceIndex for FakeSources {
|
|
fn describe_sources(&mut self, _within: Duration) -> Result<DescribedSources> {
|
|
Ok(self.state.lock().unwrap().described.clone().unwrap_or(DescribedSources::Absent))
|
|
}
|
|
|
|
fn recreate_sources(&mut self, meta: &SourcesMeta) -> Result<()> {
|
|
let mut state = self.state.lock().unwrap();
|
|
state.recreated += 1;
|
|
state.points.clear();
|
|
state.described = Some(DescribedSources::Labelled { meta: meta.clone(), cursors: BTreeMap::new() });
|
|
Ok(())
|
|
}
|
|
|
|
fn set_cursors(&mut self, cursors: &BTreeMap<String, String>) -> Result<()> {
|
|
let mut state = self.state.lock().unwrap();
|
|
state.cursor_writes.push(cursors.clone());
|
|
let Some(DescribedSources::Labelled { cursors: held, .. }) = &mut state.described else { bail!("no source collection") };
|
|
*held = cursors.clone();
|
|
Ok(())
|
|
}
|
|
|
|
fn delete_by(&mut self, repo: &str, paths: Option<&[String]>, keeping: Option<&str>) -> Result<()> {
|
|
let mut state = self.state.lock().unwrap();
|
|
if state.fail_deletes_of.as_deref() == Some(repo) {
|
|
bail!("the vector store refused the delete");
|
|
}
|
|
state.deletes.push((repo.to_owned(), paths.map(<[String]>::to_vec)));
|
|
state.points.retain(|_, point| {
|
|
!(point.payload.repo == repo
|
|
&& paths.is_none_or(|paths| paths.contains(&point.payload.path))
|
|
&& keeping.is_none_or(|commit| point.payload.commit != commit))
|
|
});
|
|
Ok(())
|
|
}
|
|
|
|
fn upsert_sources(&mut self, points: &[SourcePoint]) -> Result<()> {
|
|
let mut state = self.state.lock().unwrap();
|
|
if state.fail_upserts_after.is_some_and(|after| state.upsert_calls >= after) {
|
|
bail!("the vector store refused the upsert");
|
|
}
|
|
state.upsert_calls += 1;
|
|
for point in points {
|
|
state.points.insert(point.id.clone(), point.clone());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn search_sources(&mut self, vector: &[f32], repo: Option<&str>, front: bool, limit: u32, _within: Duration) -> Result<Vec<SourceRow>> {
|
|
let mut state = self.state.lock().unwrap();
|
|
state.searches.push((repo.map(str::to_owned), limit));
|
|
let mut rows: Vec<SourceRow> = state
|
|
.points
|
|
.values()
|
|
.filter(|point| repo.is_none_or(|repo| point.payload.repo == repo))
|
|
.filter(|point| !front || crate::sources::FRONT_PAGE_FILES.contains(&point.payload.path.as_str()))
|
|
.map(|point| SourceRow { score: cosine(vector, &point.vector), payload: point.payload.clone() })
|
|
.collect();
|
|
rows.sort_by(|a, b| b.score.total_cmp(&a.score));
|
|
rows.truncate(limit as usize);
|
|
Ok(rows)
|
|
}
|
|
}
|
|
|
|
impl SourceIndex for FakeIndex {
|
|
fn describe_sources(&mut self, within: Duration) -> Result<DescribedSources> {
|
|
self.sources.describe_sources(within)
|
|
}
|
|
fn recreate_sources(&mut self, meta: &SourcesMeta) -> Result<()> {
|
|
self.sources.recreate_sources(meta)
|
|
}
|
|
fn set_cursors(&mut self, cursors: &BTreeMap<String, String>) -> Result<()> {
|
|
self.sources.set_cursors(cursors)
|
|
}
|
|
fn delete_by(&mut self, repo: &str, paths: Option<&[String]>, keeping: Option<&str>) -> Result<()> {
|
|
self.sources.delete_by(repo, paths, keeping)
|
|
}
|
|
fn upsert_sources(&mut self, points: &[SourcePoint]) -> Result<()> {
|
|
self.sources.upsert_sources(points)
|
|
}
|
|
fn search_sources(&mut self, vector: &[f32], repo: Option<&str>, front: bool, limit: u32, within: Duration) -> Result<Vec<SourceRow>> {
|
|
self.sources.search_sources(vector, repo, front, limit, within)
|
|
}
|
|
}
|