#![allow(
clippy::expect_used,
reason = "this module is a test harness: a violated clause has to abort \
the caller's test with the clause named, and there is no other \
outcome for it to return"
)]
use std::time::Duration;
use tokio_util::sync::CancellationToken;
use crate::models::RemainingBudget;
use crate::plugin_api::{EmbedRequest, EmbeddingProviderError, EmbeddingProviderV1};
fn request(inputs: Vec<String>) -> EmbedRequest {
EmbedRequest {
inputs,
budget: RemainingBudget::starting_now(Duration::from_secs(30)),
cancel: CancellationToken::new(),
}
}
pub async fn assert_embedding_provider<P: EmbeddingProviderV1 + ?Sized>(provider: &P) {
assert_declaration(provider);
assert_alignment_and_width(provider).await;
assert_determinism(provider).await;
assert_empty_batch(provider).await;
assert_budget_and_cancellation(provider).await;
provider
.health()
.await
.expect("a provider that cannot answer `health` cannot be made ready");
}
fn assert_declaration<P: EmbeddingProviderV1 + ?Sized>(provider: &P) {
let space = provider.embedding_space();
assert_eq!(
space.dimension,
provider.dimension(),
"dimension() and embedding_space().dimension describe one space and must agree"
);
assert!(
provider.dimension() > 0,
"a zero-width space cannot rank anything"
);
assert!(
!space.identity_hash.is_empty(),
"the identity hash is what readiness compares against; an empty one \
makes every space look alike"
);
}
fn sample_inputs() -> Vec<String> {
vec![
"the first input".to_owned(),
"a second, quite different input".to_owned(),
String::new(),
]
}
async fn assert_alignment_and_width<P: EmbeddingProviderV1 + ?Sized>(provider: &P) {
let dimension = provider.dimension() as usize;
let inputs = sample_inputs();
let response = provider
.embed(request(inputs.clone()))
.await
.expect("a provider must embed a well-formed batch");
assert_eq!(
response.vectors.len(),
inputs.len(),
"vectors are aligned with inputs by index, so a short answer is a \
silent mis-assignment of every vector after the gap"
);
for (index, vector) in response.vectors.iter().enumerate() {
assert_eq!(
vector.len(),
dimension,
"vector {index} is {} wide against a declared width of {dimension}",
vector.len()
);
assert!(
vector.iter().all(|lane| lane.is_finite()),
"vector {index} carries a NaN or an infinity, which no distance \
operator can order"
);
}
assert_eq!(
&response.space,
provider.embedding_space(),
"the echoed space must be the declared one, or a mismatch is only \
discoverable at configuration time"
);
}
const DETERMINISM_TOLERANCE: f32 = 1e-4;
fn determinism_violation(first: &[Vec<f32>], second: &[Vec<f32>]) -> Option<String> {
if first.len() != second.len() {
return Some(format!(
"the same batch answered {} vectors and then {}",
first.len(),
second.len()
));
}
for (index, (a, b)) in first.iter().zip(second).enumerate() {
if a.len() != b.len() {
return Some(format!("vector {index} changed width between calls"));
}
let similarity = cosine(a, b);
if similarity < 1.0 - DETERMINISM_TOLERANCE {
return Some(format!(
"vector {index} drifted to cosine {similarity} of itself between two calls \
with the same input; the same text must embed to the same direction"
));
}
}
None
}
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();
let denominator = norm(a) * norm(b);
if denominator == 0.0 {
return if a == b { 1.0 } else { 0.0 };
}
dot / denominator
}
async fn assert_determinism<P: EmbeddingProviderV1 + ?Sized>(provider: &P) {
let inputs = sample_inputs();
let first = provider
.embed(request(inputs.clone()))
.await
.expect("a provider must embed a well-formed batch");
let second = provider
.embed(request(inputs))
.await
.expect("a provider must embed a well-formed batch");
if let Some(problem) = determinism_violation(&first.vectors, &second.vectors) {
panic!("{problem}");
}
assert_ne!(
first.vectors.first(),
first.vectors.get(1),
"two unrelated inputs embedded identically; a provider that answers a \
constant passes every other clause here"
);
}
async fn assert_empty_batch<P: EmbeddingProviderV1 + ?Sized>(provider: &P) {
let empty = provider
.embed(request(Vec::new()))
.await
.expect("an empty batch is a no-op, not an error");
assert!(
empty.vectors.is_empty(),
"an empty batch produced {} vectors",
empty.vectors.len()
);
}
async fn assert_budget_and_cancellation<P: EmbeddingProviderV1 + ?Sized>(provider: &P) {
let exhausted = EmbedRequest {
inputs: vec!["anything".to_owned()],
budget: RemainingBudget::starting_now(Duration::ZERO),
cancel: CancellationToken::new(),
};
assert!(
matches!(
provider.embed(exhausted).await,
Err(EmbeddingProviderError::Deadline)
),
"an exhausted budget must be refused as `Deadline`, not served late: \
the caller's deadline is absolute and already spent"
);
let cancel = CancellationToken::new();
cancel.cancel();
let cancelled = EmbedRequest {
inputs: vec!["anything".to_owned()],
budget: RemainingBudget::starting_now(Duration::from_secs(30)),
cancel,
};
assert!(
matches!(
provider.embed(cancelled).await,
Err(EmbeddingProviderError::Cancelled)
),
"a cancelled call must be refused as `Cancelled`"
);
}
#[cfg(test)]
mod tests {
use super::determinism_violation;
fn unit(v: &[f32]) -> Vec<f32> {
let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
v.iter().map(|x| x / norm).collect()
}
#[test]
fn last_bits_drift_is_the_same_embedding() {
let first = vec![unit(&[0.3, 0.5, 0.8, 0.1])];
let second: Vec<Vec<f32>> = first
.iter()
.map(|v| v.iter().map(|x| x + 1e-6).collect())
.collect();
assert_ne!(first, second, "the fixture must actually differ");
assert_eq!(determinism_violation(&first, &second), None);
}
#[test]
fn a_different_direction_is_not_the_same_embedding() {
let first = vec![unit(&[1.0, 0.0, 0.0, 0.0])];
let second = vec![unit(&[0.9, 0.3, 0.0, 0.0])];
let problem =
determinism_violation(&first, &second).expect("a vector that moved is refused");
assert!(problem.contains("drifted"), "{problem}");
}
#[test]
fn a_zero_vector_is_the_same_only_as_another_zero_vector() {
let zero = vec![vec![0.0_f32, 0.0, 0.0]];
assert_eq!(
determinism_violation(&zero, &zero),
None,
"a provider that answers a zero vector twice is deterministic"
);
let other = vec![unit(&[1.0, 0.0, 0.0])];
assert!(
determinism_violation(&zero, &other).is_some(),
"a zero vector and then a real one is not the same embedding"
);
assert!(
determinism_violation(&other, &zero).is_some(),
"nor the other way round"
);
}
#[test]
fn a_changed_shape_is_refused() {
let one = vec![unit(&[1.0, 2.0])];
assert!(
determinism_violation(&one, &[]).is_some(),
"a vector went missing"
);
assert!(
determinism_violation(&one, &[unit(&[1.0, 2.0, 3.0])]).is_some(),
"a vector changed width"
);
}
}