- add a transport client for one current backend protocol with loopback http, TLS-only remote endpoints, explicit remote consent, disabled redirects, bounded timeout/batch/payload/response/dimension and no credential in URLs - validate responses strictly (count, index order, dimension, finite values, non-zero norm, mixed-model rejection) and abort publication when any vector is missing so a mixed index is never stored - embed search units in the same transaction that writes the projection, with content-digest/model-digest guarded reuse for incremental compiles; the build metadata records endpoint/model/revision/dimension/distance/chunking - add the semantic query channel behind explicit --semantic using an exact cosine scan with a bounded vector budget; default queries stay completely offline even when vectors exist - add a local mock-server integration test proving protocol handling, cross-vocabulary recall, offline default behaviour, remote consent rules and all-or-nothing failure; real-model quality remains NOT RUN and is not claimed
540 lines
19 KiB
Rust
540 lines
19 KiB
Rust
//! OpenAI-compatible embeddings transport (one current backend protocol).
|
|
//!
|
|
//! Semantic indexing is explicit. The client sends only the selected snippets
|
|
//! and the query, never the workspace, paths or unrelated metadata. The API key
|
|
//! comes from the environment and is never stored, logged or printed.
|
|
//!
|
|
//! Safety rules:
|
|
//! * no implicit network: construction only validates configuration;
|
|
//! * remote endpoints require explicit consent, HTTPS and disabled redirects;
|
|
//! * loopback HTTP is allowed for a locally deployed compatible service;
|
|
//! * bounded timeout, batch size, response size and dimension;
|
|
//! * strict response validation: count, order, dimension, finite values and
|
|
//! non-zero norm; mixed models/dimensions are rejected.
|
|
|
|
use crate::error::KnowledgeError;
|
|
use crate::model::sha256_prefixed;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::time::Duration;
|
|
|
|
pub const API_KEY_ENV: &str = "MARQDO_KNOWLEDGE_EMBEDDING_API_KEY";
|
|
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
|
pub const MAX_BATCH: usize = 64;
|
|
pub const MAX_UNITS: usize = 20_000;
|
|
pub const MAX_DIMENSION: usize = 8_192;
|
|
pub const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024;
|
|
pub const MAX_INPUT_CHARS: usize = 2_000;
|
|
pub const MAX_ATTEMPTS: usize = 2;
|
|
pub const DISTANCE: &str = "cosine";
|
|
pub const CHUNKING: &str = "search_unit_title_body";
|
|
|
|
/// User-supplied embedding options.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct EmbeddingConfig {
|
|
endpoint: String,
|
|
model: String,
|
|
revision: String,
|
|
allow_remote: bool,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
struct UrlParts {
|
|
scheme: String,
|
|
host: String,
|
|
port: Option<u16>,
|
|
path: String,
|
|
}
|
|
|
|
impl EmbeddingConfig {
|
|
pub fn new(
|
|
url: &str,
|
|
model: &str,
|
|
revision: &str,
|
|
allow_remote: bool,
|
|
) -> Result<Self, KnowledgeError> {
|
|
let config = Self {
|
|
endpoint: url.trim().to_string(),
|
|
model: model.trim().to_string(),
|
|
revision: revision.trim().to_string(),
|
|
allow_remote,
|
|
};
|
|
config.validate()?;
|
|
Ok(config)
|
|
}
|
|
|
|
pub fn model(&self) -> &str {
|
|
&self.model
|
|
}
|
|
|
|
pub fn revision(&self) -> &str {
|
|
&self.revision
|
|
}
|
|
|
|
/// Sanitised endpoint without credentials, query or fragment.
|
|
pub fn endpoint(&self) -> Result<String, KnowledgeError> {
|
|
let parts = parse_url(&self.endpoint)?;
|
|
Ok(format!(
|
|
"{}://{}{}{}",
|
|
parts.scheme,
|
|
parts.host,
|
|
parts
|
|
.port
|
|
.map(|port| format!(":{port}"))
|
|
.unwrap_or_default(),
|
|
parts.path
|
|
))
|
|
}
|
|
|
|
pub fn validate(&self) -> Result<(), KnowledgeError> {
|
|
if self.model.is_empty() || self.revision.is_empty() {
|
|
return Err(KnowledgeError::usage(
|
|
"embedding model and revision must not be empty",
|
|
));
|
|
}
|
|
let parts = parse_url(&self.endpoint)?;
|
|
let loopback = is_loopback(&parts.host);
|
|
if !loopback {
|
|
if parts.scheme != "https" {
|
|
return Err(KnowledgeError::environment(
|
|
crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED,
|
|
"remote embeddings require TLS (https); plain http is only allowed for loopback services",
|
|
));
|
|
}
|
|
if !self.allow_remote {
|
|
return Err(KnowledgeError::environment(
|
|
crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED,
|
|
"remote embeddings require explicit --allow-remote-embedding consent",
|
|
)
|
|
.with_hint("the query/index content would leave this machine"));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Stable digest of the index configuration (never includes the API key).
|
|
pub fn model_digest(&self, dimension: usize) -> Result<String, KnowledgeError> {
|
|
let endpoint = self.endpoint()?;
|
|
let canonical = format!(
|
|
"endpoint={endpoint}|model={}|revision={}|dimension={dimension}|distance={DISTANCE}|chunking={CHUNKING}",
|
|
self.model, self.revision
|
|
);
|
|
Ok(sha256_prefixed(canonical.as_bytes()))
|
|
}
|
|
}
|
|
|
|
fn parse_url(url: &str) -> Result<UrlParts, KnowledgeError> {
|
|
let Some(scheme_end) = url.find("://") else {
|
|
return Err(KnowledgeError::usage(
|
|
"embedding endpoint must be an absolute http(s) URL",
|
|
));
|
|
};
|
|
let scheme = url[..scheme_end].to_ascii_lowercase();
|
|
if scheme != "http" && scheme != "https" {
|
|
return Err(KnowledgeError::usage(
|
|
"embedding endpoint scheme must be http or https",
|
|
));
|
|
}
|
|
if url.contains('?') || url.contains('#') {
|
|
return Err(KnowledgeError::usage(
|
|
"embedding endpoint must not contain a query or fragment",
|
|
));
|
|
}
|
|
let rest = &url[scheme_end + 3..];
|
|
let (authority, path) = match rest.split_once('/') {
|
|
Some((authority, path)) => (authority, format!("/{path}")),
|
|
None => (rest, "/".to_string()),
|
|
};
|
|
if authority.is_empty() {
|
|
return Err(KnowledgeError::usage("embedding endpoint has no host"));
|
|
}
|
|
if authority.contains('@') {
|
|
return Err(KnowledgeError::usage(
|
|
"credentials must not be embedded in the embedding endpoint URL",
|
|
));
|
|
}
|
|
let (host, port) = if let Some(stripped) = authority.strip_prefix('[') {
|
|
// IPv6 literal.
|
|
let Some((host, rest)) = stripped.split_once(']') else {
|
|
return Err(KnowledgeError::usage(
|
|
"invalid IPv6 host in embedding endpoint",
|
|
));
|
|
};
|
|
let port = match rest.strip_prefix(':') {
|
|
Some(port) => Some(
|
|
port.parse::<u16>()
|
|
.map_err(|_| KnowledgeError::usage("invalid embedding endpoint port"))?,
|
|
),
|
|
None => None,
|
|
};
|
|
(format!("[{host}]"), port)
|
|
} else {
|
|
match authority.rsplit_once(':') {
|
|
Some((host, port)) if !host.contains(':') => (
|
|
host.to_string(),
|
|
Some(
|
|
port.parse::<u16>()
|
|
.map_err(|_| KnowledgeError::usage("invalid embedding endpoint port"))?,
|
|
),
|
|
),
|
|
_ => (authority.to_string(), None),
|
|
}
|
|
};
|
|
if host.is_empty() {
|
|
return Err(KnowledgeError::usage("embedding endpoint has no host"));
|
|
}
|
|
Ok(UrlParts {
|
|
scheme,
|
|
host,
|
|
port,
|
|
path,
|
|
})
|
|
}
|
|
|
|
fn is_loopback(host: &str) -> bool {
|
|
let host = host.trim_start_matches('[').trim_end_matches(']');
|
|
matches!(host, "127.0.0.1" | "::1" | "localhost") || host.starts_with("127.")
|
|
}
|
|
|
|
/// Index configuration persisted in build metadata.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct EmbeddingMeta {
|
|
pub endpoint: String,
|
|
pub model: String,
|
|
pub revision: String,
|
|
pub dimension: usize,
|
|
pub distance: String,
|
|
pub model_digest: String,
|
|
pub chunking: String,
|
|
pub max_input_chars: usize,
|
|
}
|
|
|
|
/// Precomputed vectors for the publish transaction.
|
|
#[derive(Debug, Clone)]
|
|
pub struct EmbeddingVectors {
|
|
pub model_digest: String,
|
|
pub dimension: usize,
|
|
/// (node canonical key, unit span start, embedded-text digest) -> vector.
|
|
pub vectors: std::collections::HashMap<(String, u64, String), Vec<f32>>,
|
|
}
|
|
|
|
/// One text that must be embedded, keyed by its search-unit identity.
|
|
#[derive(Debug, Clone)]
|
|
pub struct EmbeddingSource {
|
|
pub node_key: String,
|
|
pub span_start: u64,
|
|
pub content_digest: String,
|
|
pub text: String,
|
|
}
|
|
|
|
/// Build the exact text used for chunk embeddings. Deterministic and bounded.
|
|
pub fn embedding_text(title: &str, body: &str, formula: &str) -> String {
|
|
let mut text = String::new();
|
|
if !title.is_empty() {
|
|
text.push_str(title);
|
|
text.push('\n');
|
|
}
|
|
text.push_str(body);
|
|
if !formula.is_empty() {
|
|
text.push('\n');
|
|
text.push_str(formula);
|
|
}
|
|
let mut end = text.len().min(MAX_INPUT_CHARS * 4);
|
|
while end > 0 && !text.is_char_boundary(end) {
|
|
end -= 1;
|
|
}
|
|
text.truncate(end);
|
|
text
|
|
}
|
|
|
|
/// Digest of the exact embedded text, used for reuse and invalidation.
|
|
pub fn embedding_content_digest(text: &str) -> String {
|
|
sha256_prefixed(text.as_bytes())
|
|
}
|
|
|
|
pub struct EmbeddingClient {
|
|
agent: ureq::Agent,
|
|
url: String,
|
|
model: String,
|
|
api_key: Option<String>,
|
|
}
|
|
|
|
impl EmbeddingClient {
|
|
pub fn new(config: &EmbeddingConfig) -> Result<Self, KnowledgeError> {
|
|
config.validate()?;
|
|
let url = config.endpoint()?;
|
|
let agent_config = ureq::Agent::config_builder()
|
|
.timeout_global(Some(REQUEST_TIMEOUT))
|
|
.max_redirects(0)
|
|
.build();
|
|
let agent: ureq::Agent = agent_config.into();
|
|
Ok(Self {
|
|
agent,
|
|
url,
|
|
model: config.model.clone(),
|
|
api_key: std::env::var(API_KEY_ENV)
|
|
.ok()
|
|
.filter(|key| !key.is_empty()),
|
|
})
|
|
}
|
|
|
|
pub fn endpoint(&self) -> &str {
|
|
&self.url
|
|
}
|
|
|
|
/// Embed bounded batches. Every batch is validated before being accepted.
|
|
pub fn embed(&self, inputs: &[String]) -> Result<(Vec<Vec<f32>>, usize), KnowledgeError> {
|
|
if inputs.is_empty() {
|
|
return Err(KnowledgeError::environment(
|
|
crate::diagnostic::code::EMBEDDING_UNAVAILABLE,
|
|
"no search units to embed",
|
|
));
|
|
}
|
|
if inputs.len() > MAX_UNITS {
|
|
return Err(KnowledgeError::environment(
|
|
crate::diagnostic::code::BUDGET_EXCEEDED,
|
|
format!(
|
|
"{} embedding inputs exceed the {MAX_UNITS} unit budget",
|
|
inputs.len()
|
|
),
|
|
));
|
|
}
|
|
let mut vectors = Vec::with_capacity(inputs.len());
|
|
let mut dimension = 0usize;
|
|
for batch in inputs.chunks(MAX_BATCH) {
|
|
let batch_vectors = self.embed_batch(batch)?;
|
|
for vector in batch_vectors {
|
|
if dimension == 0 {
|
|
dimension = vector.len();
|
|
} else if vector.len() != dimension {
|
|
return Err(invalid_response(
|
|
"embedding dimension changed between batches",
|
|
));
|
|
}
|
|
vectors.push(vector);
|
|
}
|
|
}
|
|
Ok((vectors, dimension))
|
|
}
|
|
|
|
fn embed_batch(&self, inputs: &[String]) -> Result<Vec<Vec<f32>>, KnowledgeError> {
|
|
let payload = serde_json::json!({"model": self.model, "input": inputs});
|
|
let mut last_error = None;
|
|
for attempt in 0..MAX_ATTEMPTS {
|
|
match self.send(&payload) {
|
|
Ok(response) => return validate_response(response, inputs.len()),
|
|
Err(error)
|
|
if error.code == crate::diagnostic::code::EMBEDDING_TRANSPORT
|
|
&& attempt + 1 < MAX_ATTEMPTS =>
|
|
{
|
|
last_error = Some(error);
|
|
std::thread::sleep(Duration::from_millis(200));
|
|
}
|
|
Err(error) => return Err(error),
|
|
}
|
|
}
|
|
Err(last_error
|
|
.unwrap_or_else(|| invalid_response("embedding request failed without a response")))
|
|
}
|
|
|
|
fn send(&self, payload: &serde_json::Value) -> Result<serde_json::Value, KnowledgeError> {
|
|
if payload.to_string().len() > MAX_RESPONSE_BYTES {
|
|
return Err(KnowledgeError::environment(
|
|
crate::diagnostic::code::BUDGET_EXCEEDED,
|
|
"embedding request payload exceeds the size budget",
|
|
));
|
|
}
|
|
let mut request = self
|
|
.agent
|
|
.post(&self.url)
|
|
.header("content-type", "application/json");
|
|
if let Some(key) = &self.api_key {
|
|
request = request.header("authorization", format!("Bearer {key}"));
|
|
}
|
|
let mut response = request.send_json(payload).map_err(|error| {
|
|
KnowledgeError::environment(
|
|
crate::diagnostic::code::EMBEDDING_TRANSPORT,
|
|
format!("embedding endpoint request failed: {error}"),
|
|
)
|
|
})?;
|
|
let body = response.body_mut().read_to_string().map_err(|error| {
|
|
KnowledgeError::environment(
|
|
crate::diagnostic::code::EMBEDDING_TRANSPORT,
|
|
format!("embedding response could not be read: {error}"),
|
|
)
|
|
})?;
|
|
if body.len() > MAX_RESPONSE_BYTES {
|
|
return Err(KnowledgeError::environment(
|
|
crate::diagnostic::code::BUDGET_EXCEEDED,
|
|
"embedding response exceeds the size budget",
|
|
));
|
|
}
|
|
serde_json::from_str(&body).map_err(|error| {
|
|
invalid_response(&format!("embedding response is not valid JSON: {error}"))
|
|
})
|
|
}
|
|
}
|
|
|
|
fn invalid_response(message: &str) -> KnowledgeError {
|
|
KnowledgeError::environment(
|
|
crate::diagnostic::code::EMBEDDING_INVALID_RESPONSE,
|
|
message.to_string(),
|
|
)
|
|
}
|
|
|
|
fn validate_response(
|
|
response: serde_json::Value,
|
|
expected: usize,
|
|
) -> Result<Vec<Vec<f32>>, KnowledgeError> {
|
|
let Some(data) = response.get("data").and_then(|data| data.as_array()) else {
|
|
return Err(invalid_response("embedding response has no `data` array"));
|
|
};
|
|
if data.len() != expected {
|
|
return Err(invalid_response(&format!(
|
|
"embedding response returned {} vector(s) for {expected} input(s)",
|
|
data.len()
|
|
)));
|
|
}
|
|
let mut vectors: Vec<Option<Vec<f32>>> = vec![None; expected];
|
|
for item in data {
|
|
let index = item
|
|
.get("index")
|
|
.and_then(|index| index.as_u64())
|
|
.ok_or_else(|| invalid_response("embedding item has no integer `index`"))?
|
|
as usize;
|
|
if index >= expected {
|
|
return Err(invalid_response("embedding item index is out of range"));
|
|
}
|
|
if vectors[index].is_some() {
|
|
return Err(invalid_response("embedding response repeats an item index"));
|
|
}
|
|
let embedding = item
|
|
.get("embedding")
|
|
.and_then(|embedding| embedding.as_array())
|
|
.ok_or_else(|| invalid_response("embedding item has no vector"))?;
|
|
if embedding.is_empty() || embedding.len() > MAX_DIMENSION {
|
|
return Err(invalid_response(
|
|
"embedding dimension is empty or too large",
|
|
));
|
|
}
|
|
let mut vector = Vec::with_capacity(embedding.len());
|
|
let mut norm_squared = 0.0f64;
|
|
for value in embedding {
|
|
let value = value
|
|
.as_f64()
|
|
.ok_or_else(|| invalid_response("embedding value is not a finite number"))?;
|
|
if !value.is_finite() {
|
|
return Err(invalid_response("embedding value is not finite"));
|
|
}
|
|
vector.push(value as f32);
|
|
norm_squared += value * value;
|
|
}
|
|
if norm_squared <= 1e-12 {
|
|
return Err(invalid_response("embedding vector has zero norm"));
|
|
}
|
|
vectors[index] = Some(vector);
|
|
}
|
|
let mut out = Vec::with_capacity(expected);
|
|
for vector in vectors {
|
|
out.push(vector.ok_or_else(|| invalid_response("embedding response is missing an item"))?);
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Cosine similarity of two equal-length vectors. Returns `None` for invalid
|
|
/// input; the caller never compares different dimensions.
|
|
pub fn cosine(left: &[f32], right: &[f32]) -> Option<f64> {
|
|
if left.len() != right.len() || left.is_empty() {
|
|
return None;
|
|
}
|
|
let mut dot = 0.0f64;
|
|
let mut left_norm = 0.0f64;
|
|
let mut right_norm = 0.0f64;
|
|
for (a, b) in left.iter().zip(right.iter()) {
|
|
let a = f64::from(*a);
|
|
let b = f64::from(*b);
|
|
if !a.is_finite() || !b.is_finite() {
|
|
return None;
|
|
}
|
|
dot += a * b;
|
|
left_norm += a * a;
|
|
right_norm += b * b;
|
|
}
|
|
if left_norm <= 0.0 || right_norm <= 0.0 {
|
|
return None;
|
|
}
|
|
Some(dot / (left_norm.sqrt() * right_norm.sqrt()))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn loopback_http_is_allowed_but_remote_http_is_not() {
|
|
assert!(EmbeddingConfig::new("http://127.0.0.1:8080/v1", "m", "r", false).is_ok());
|
|
assert!(EmbeddingConfig::new("http://localhost:8080/v1", "m", "r", false).is_ok());
|
|
let error = EmbeddingConfig::new("http://example.com/v1", "m", "r", true).unwrap_err();
|
|
assert_eq!(
|
|
error.code,
|
|
crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED
|
|
);
|
|
let error = EmbeddingConfig::new("https://example.com/v1", "m", "r", false).unwrap_err();
|
|
assert_eq!(
|
|
error.code,
|
|
crate::diagnostic::code::EMBEDDING_REMOTE_NOT_ALLOWED
|
|
);
|
|
let error = EmbeddingConfig::new("https://example.com/v1?x=1", "m", "r", true).unwrap_err();
|
|
assert!(error.message.contains("query") || error.message.contains("fragment"));
|
|
assert!(EmbeddingConfig::new("https://user:pass@example.com/v1", "m", "r", true).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn model_digest_is_stable_and_excludes_secrets() {
|
|
let config =
|
|
EmbeddingConfig::new("http://127.0.0.1:8080/v1/", "model", "r1", false).unwrap();
|
|
let first = config.model_digest(3).unwrap();
|
|
let second = config.model_digest(3).unwrap();
|
|
assert_eq!(first, second);
|
|
assert!(first.starts_with("sha256:"));
|
|
let other = config.model_digest(4).unwrap();
|
|
assert_ne!(first, other);
|
|
}
|
|
|
|
#[test]
|
|
fn response_validation_rejects_bad_shapes() {
|
|
let good = serde_json::json!({"data": [
|
|
{"index": 0, "embedding": [1.0, 0.0]},
|
|
{"index": 1, "embedding": [0.0, 1.0]}
|
|
]});
|
|
assert_eq!(validate_response(good, 2).unwrap().len(), 2);
|
|
let wrong_count = serde_json::json!({"data": [{"index": 0, "embedding": [1.0]}]});
|
|
assert!(validate_response(wrong_count, 2).is_err());
|
|
let zero = serde_json::json!({"data": [{"index": 0, "embedding": [0.0, 0.0]}]});
|
|
assert!(validate_response(zero, 1).is_err());
|
|
let duplicate = serde_json::json!({"data": [
|
|
{"index": 0, "embedding": [1.0]},
|
|
{"index": 0, "embedding": [1.0]}
|
|
]});
|
|
assert!(validate_response(duplicate, 2).is_err());
|
|
let huge = serde_json::json!({"data": [{"index": 0, "embedding": [1e300]}]});
|
|
assert!(validate_response(huge, 1).is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn cosine_is_bounded_and_rejects_mismatch() {
|
|
assert!(cosine(&[1.0, 0.0], &[1.0, 0.0]).unwrap() > 0.999);
|
|
assert!(cosine(&[1.0, 0.0], &[0.0, 1.0]).unwrap() < 0.001);
|
|
assert!(cosine(&[1.0], &[1.0, 2.0]).is_none());
|
|
assert!(cosine(&[0.0, 0.0], &[1.0, 0.0]).is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn embedding_text_is_bounded_on_char_boundaries() {
|
|
let long = "量子".repeat(10_000);
|
|
let text = embedding_text("title", &long, "F=ma");
|
|
assert!(text.len() <= MAX_INPUT_CHARS * 4);
|
|
assert!(std::str::from_utf8(text.as_bytes()).is_ok());
|
|
assert_eq!(embedding_content_digest("abc"), sha256_prefixed(b"abc"));
|
|
}
|
|
}
|