memory: per-session semantic memory (strata-memory crate, Qdrant Edge + BGE-M3)
remember/recall/forget agent tools, one-way opt-in latch with embedder gate, fail-open Store-authoritative design, keyword fallback, model-id rebuild, GUI toggle + i18n; docs updated; split-debuginfo=unpacked
This commit is contained in:
1 parent
6898cdf113
commit
f74d53e446
24 files changed
+4853
-67
No files matched your search
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "strata-memory"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
description = "strata-ctl semantic memory: swappable Embedder trait + HTTP (BGE-M3) backend, Qdrant Edge index"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
# Blocking HTTP client (matches strata-ctl's existing choice). `json` enables send_json.
|
||||
ureq = { version = "3.5.2", features = ["json"] }
|
||||
# In-process Qdrant engine (single shard, disk-backed). The semantic index over
|
||||
# memory records; rebuildable/disposable. Pinned: pre-1.0 beta.
|
||||
qdrant-edge = "0.9"
|
||||
|
||||
[dev-dependencies]
|
||||
# Temporary shard directories for hermetic in-process index tests.
|
||||
tempfile = "3"
|
||||
@@ -0,0 +1,501 @@
|
||||
//! Semantic index over memory records, backed by an in-process Qdrant Edge shard.
|
||||
//!
|
||||
//! Architecture (ratified): the relational Store owns the authoritative records;
|
||||
//! this index is a REBUILDABLE/DISPOSABLE semantic layer over them. Vectors live
|
||||
//! only here; what reaches the model is text + score (see the symbolic-vector
|
||||
//! principle). The payload carries a copy of the record so recall can render
|
||||
//! without a Store round-trip; on embedder swap the whole shard is rebuilt.
|
||||
//!
|
||||
//! Dense-only baseline (no sparse/ColBERT). Soft-delete via a `dead` payload flag
|
||||
//! filtered out of every query (pattern from our Iris Qdrant backend).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use qdrant_edge::{
|
||||
Condition, Distance, EdgeConfigBuilder, EdgeShard, EdgeVectorParams, FieldCondition, Filter,
|
||||
Match, NamedQuery, Payload, PayloadOps, PointInsertOperations, PointOperations, PointStruct,
|
||||
QueryEnum, QueryRequestBuilder, ScoringQuery, ScrollRequestBuilder, SetPayloadOp,
|
||||
UpdateOperation, ValueVariants, VectorInternal, Vectors, WithPayloadInterface, WithVector,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{EmbedError, Embedder};
|
||||
|
||||
/// Named dense vector in the shard.
|
||||
pub const DENSE_VECTOR_NAME: &str = "dense";
|
||||
/// Sidecar file recording which embedder built the shard (rebuild-on-swap guard).
|
||||
const MODEL_FILE: &str = "strata_model.json";
|
||||
|
||||
/// The authoritative memory record shape. The relational Store owns these; the
|
||||
/// index keeps a rebuildable copy in the point payload.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MemoryRecord {
|
||||
pub id: String,
|
||||
pub category: String,
|
||||
pub title: String,
|
||||
pub content: String,
|
||||
pub keywords: Vec<String>,
|
||||
pub scope: String,
|
||||
pub timestamp: String,
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
/// A recall hit: the record (text) + its relevance score. No vector ever leaves.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Hit {
|
||||
pub record: MemoryRecord,
|
||||
pub score: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum IndexError {
|
||||
#[error("qdrant: {0}")]
|
||||
Qdrant(String),
|
||||
#[error("io: {0}")]
|
||||
Io(String),
|
||||
#[error("serde: {0}")]
|
||||
Serde(String),
|
||||
#[error(transparent)]
|
||||
Embed(#[from] EmbedError),
|
||||
#[error("model mismatch: index built with '{index}' (dim {index_dim}), current '{current}' (dim {current_dim}) — rebuild required")]
|
||||
ModelMismatch {
|
||||
index: String,
|
||||
index_dim: usize,
|
||||
current: String,
|
||||
current_dim: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<qdrant_edge::OperationError> for IndexError {
|
||||
fn from(e: qdrant_edge::OperationError) -> Self {
|
||||
IndexError::Qdrant(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ModelTag {
|
||||
model_id: String,
|
||||
dim: usize,
|
||||
}
|
||||
|
||||
/// In-process semantic index. Holds the embedder so `upsert`/`search` can embed
|
||||
/// text directly; the caller never handles raw vectors.
|
||||
pub struct MemoryIndex {
|
||||
shard: EdgeShard,
|
||||
dim: usize,
|
||||
model_id: String,
|
||||
embedder: Arc<dyn Embedder>,
|
||||
}
|
||||
|
||||
impl MemoryIndex {
|
||||
/// Open (or create) a shard at `path`. If it already exists, its embedder tag
|
||||
/// must match `model_id`/`dim`, else [`IndexError::ModelMismatch`] is returned
|
||||
/// so the caller can rebuild rather than mix incompatible vectors.
|
||||
pub fn open(
|
||||
path: impl AsRef<Path>,
|
||||
dim: usize,
|
||||
model_id: impl Into<String>,
|
||||
embedder: Arc<dyn Embedder>,
|
||||
) -> Result<Self, IndexError> {
|
||||
let path = path.as_ref();
|
||||
let model_id = model_id.into();
|
||||
let model_file = path.join(MODEL_FILE);
|
||||
|
||||
if path.join("edge_config.json").exists() {
|
||||
let shard = EdgeShard::load(path, None)?;
|
||||
let tag = read_tag(&model_file)?;
|
||||
if tag.model_id != model_id || tag.dim != dim {
|
||||
return Err(IndexError::ModelMismatch {
|
||||
index: tag.model_id,
|
||||
index_dim: tag.dim,
|
||||
current: model_id,
|
||||
current_dim: dim,
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
shard,
|
||||
dim,
|
||||
model_id,
|
||||
embedder,
|
||||
})
|
||||
} else {
|
||||
std::fs::create_dir_all(path).map_err(|e| IndexError::Io(e.to_string()))?;
|
||||
let config = EdgeConfigBuilder::new()
|
||||
.vector(
|
||||
DENSE_VECTOR_NAME,
|
||||
EdgeVectorParams::builder(dim, Distance::Cosine).build(),
|
||||
)
|
||||
.build();
|
||||
let shard = EdgeShard::new(path, config)?;
|
||||
write_tag(
|
||||
&model_file,
|
||||
&ModelTag {
|
||||
model_id: model_id.clone(),
|
||||
dim,
|
||||
},
|
||||
)?;
|
||||
Ok(Self {
|
||||
shard,
|
||||
dim,
|
||||
model_id,
|
||||
embedder,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dim(&self) -> usize {
|
||||
self.dim
|
||||
}
|
||||
|
||||
pub fn model_id(&self) -> &str {
|
||||
&self.model_id
|
||||
}
|
||||
|
||||
/// Probe whether the embedder responds (gate for enabling memory on a session).
|
||||
/// One tiny embed; true iff it succeeds. Trait-generic, so it also works for the
|
||||
/// future in-process embedder.
|
||||
pub fn embedder_reachable(&self) -> bool {
|
||||
self.embedder.embed(&["ping"]).is_ok()
|
||||
}
|
||||
|
||||
/// Embed the record's content and upsert it (idempotent on the record id).
|
||||
pub fn upsert(&self, record: &MemoryRecord) -> Result<(), IndexError> {
|
||||
let vector = self
|
||||
.embedder
|
||||
.embed(&[record.content.as_str()])?
|
||||
.pop()
|
||||
.ok_or_else(|| EmbedError::Shape("embedder returned no vector".into()))?;
|
||||
if vector.len() != self.dim {
|
||||
return Err(IndexError::Qdrant(format!(
|
||||
"vector dim {} != index dim {}",
|
||||
vector.len(),
|
||||
self.dim
|
||||
)));
|
||||
}
|
||||
let mut payload =
|
||||
serde_json::to_value(record).map_err(|e| IndexError::Serde(e.to_string()))?;
|
||||
payload["dead"] = serde_json::json!(false);
|
||||
let point = PointStruct::new(
|
||||
point_id(&record.id),
|
||||
Vectors::new_named([(DENSE_VECTOR_NAME, vector)]),
|
||||
payload,
|
||||
);
|
||||
self.shard.update(UpdateOperation::PointOperation(
|
||||
PointOperations::UpsertPoints(PointInsertOperations::PointsList(vec![point.into()])),
|
||||
))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Semantic recall: embed `query`, return up to `top_k` live records scoring
|
||||
/// at least `threshold`, optionally filtered by category/scope. Tombstones
|
||||
/// (`dead=true`) are always excluded.
|
||||
pub fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
top_k: usize,
|
||||
threshold: f32,
|
||||
category: Option<&str>,
|
||||
scope: Option<&str>,
|
||||
) -> Result<Vec<Hit>, IndexError> {
|
||||
let vector = self
|
||||
.embedder
|
||||
.embed(&[query])?
|
||||
.pop()
|
||||
.ok_or_else(|| EmbedError::Shape("embedder returned no vector".into()))?;
|
||||
self.search_vector(&vector, top_k, threshold, category, scope)
|
||||
}
|
||||
|
||||
/// Vector-level search (also used by the symbolic workspace bridge: a
|
||||
/// `$VEC[n]` resolved server-side is fed here without entering context).
|
||||
pub fn search_vector(
|
||||
&self,
|
||||
vector: &[f32],
|
||||
top_k: usize,
|
||||
threshold: f32,
|
||||
category: Option<&str>,
|
||||
scope: Option<&str>,
|
||||
) -> Result<Vec<Hit>, IndexError> {
|
||||
let scoring = ScoringQuery::Vector(QueryEnum::Nearest(NamedQuery::new(
|
||||
VectorInternal::from(vector.to_vec()),
|
||||
DENSE_VECTOR_NAME.to_string(),
|
||||
)));
|
||||
let request = QueryRequestBuilder::new(top_k)
|
||||
.query(scoring)
|
||||
.filter(live_filter(category, scope))
|
||||
.score_threshold(threshold)
|
||||
.with_payload(WithPayloadInterface::Bool(true))
|
||||
.with_vector(WithVector::Bool(false))
|
||||
.build();
|
||||
let points = self.shard.query(request)?;
|
||||
let mut hits = Vec::with_capacity(points.len());
|
||||
for p in points {
|
||||
if let Some(record) = payload_to_record(p.payload.as_ref()) {
|
||||
hits.push(Hit {
|
||||
record,
|
||||
score: p.score,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(hits)
|
||||
}
|
||||
|
||||
/// Soft-delete: mark the record `dead=true` so it is excluded from recall but
|
||||
/// retained for rebuild/audit. The authoritative removal happens in the Store.
|
||||
pub fn mark_dead(&self, id: &str) -> Result<(), IndexError> {
|
||||
let payload = Payload::from(
|
||||
serde_json::json!({ "dead": true })
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
);
|
||||
let op = SetPayloadOp {
|
||||
payload,
|
||||
points: None,
|
||||
filter: Some(Filter::new_must(field_match_str("id", id))),
|
||||
key: None,
|
||||
};
|
||||
self.shard
|
||||
.update(UpdateOperation::PayloadOperation(PayloadOps::SetPayload(
|
||||
op,
|
||||
)))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persist WAL + segments to disk.
|
||||
pub fn flush(&self) -> Result<(), IndexError> {
|
||||
self.shard.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every record id present in the shard, INCLUDING tombstones. Used by the
|
||||
/// service to reconcile the authoritative Store against the index (find records
|
||||
/// that were saved while the embedder was down) without re-embedding everything.
|
||||
/// Tombstones are included on purpose so a soft-deleted record is not resurrected.
|
||||
pub fn indexed_ids(&self) -> Result<Vec<String>, IndexError> {
|
||||
let mut ids = Vec::new();
|
||||
let mut offset = None;
|
||||
loop {
|
||||
let mut req = ScrollRequestBuilder::new()
|
||||
.limit(256)
|
||||
.with_payload(WithPayloadInterface::Bool(true))
|
||||
.with_vector(WithVector::Bool(false));
|
||||
if let Some(o) = offset {
|
||||
req = req.offset(o);
|
||||
}
|
||||
let (records, next) = self.shard.scroll(req.build())?;
|
||||
for r in records {
|
||||
if let Some(id) = r
|
||||
.payload
|
||||
.as_ref()
|
||||
.and_then(|p| p.0.get("id"))
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
ids.push(id.to_string());
|
||||
}
|
||||
}
|
||||
match next {
|
||||
Some(o) => offset = Some(o),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
}
|
||||
|
||||
// ── helpers ──
|
||||
|
||||
/// Stable numeric point id from the record id (FNV-1a). The authoritative string
|
||||
/// id is kept in the payload; the numeric id only needs to be deterministic so a
|
||||
/// re-upsert of the same record overwrites its point.
|
||||
fn point_id(id: &str) -> u64 {
|
||||
let mut h: u64 = 0xcbf29ce484222325;
|
||||
for b in id.bytes() {
|
||||
h ^= b as u64;
|
||||
h = h.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
fn field_match_str(key: &str, value: &str) -> Condition {
|
||||
Condition::Field(FieldCondition::new_match(
|
||||
key.parse().expect("valid payload key"),
|
||||
Match::new_value(ValueVariants::String(value.to_string())),
|
||||
))
|
||||
}
|
||||
|
||||
fn dead_condition() -> Condition {
|
||||
Condition::Field(FieldCondition::new_match(
|
||||
"dead".parse().expect("valid payload key"),
|
||||
Match::new_value(ValueVariants::Bool(true)),
|
||||
))
|
||||
}
|
||||
|
||||
/// Every query excludes tombstones; optional category/scope are `must` matches.
|
||||
fn live_filter(category: Option<&str>, scope: Option<&str>) -> Filter {
|
||||
let mut must = Vec::new();
|
||||
if let Some(c) = category {
|
||||
must.push(field_match_str("category", c));
|
||||
}
|
||||
if let Some(s) = scope {
|
||||
must.push(field_match_str("scope", s));
|
||||
}
|
||||
Filter {
|
||||
must: if must.is_empty() { None } else { Some(must) },
|
||||
must_not: Some(vec![dead_condition()]),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn payload_to_record(payload: Option<&Payload>) -> Option<MemoryRecord> {
|
||||
let map = &payload?.0;
|
||||
let mut value = serde_json::Value::Object(map.clone());
|
||||
if let Some(obj) = value.as_object_mut() {
|
||||
obj.remove("dead");
|
||||
}
|
||||
serde_json::from_value(value).ok()
|
||||
}
|
||||
|
||||
fn read_tag(path: &PathBuf) -> Result<ModelTag, IndexError> {
|
||||
let data = std::fs::read_to_string(path).map_err(|e| IndexError::Io(e.to_string()))?;
|
||||
serde_json::from_str(&data).map_err(|e| IndexError::Serde(e.to_string()))
|
||||
}
|
||||
|
||||
fn write_tag(path: &Path, tag: &ModelTag) -> Result<(), IndexError> {
|
||||
let data = serde_json::to_string(tag).map_err(|e| IndexError::Serde(e.to_string()))?;
|
||||
std::fs::write(path, data).map_err(|e| IndexError::Io(e.to_string()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Deterministic embedder: maps a few known texts to orthogonal unit vectors.
|
||||
struct StubEmbedder;
|
||||
impl Embedder for StubEmbedder {
|
||||
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, EmbedError> {
|
||||
Ok(texts
|
||||
.iter()
|
||||
.map(|t| match *t {
|
||||
"alpha" => vec![1.0, 0.0, 0.0, 0.0],
|
||||
"beta" => vec![0.0, 1.0, 0.0, 0.0],
|
||||
_ => vec![0.0, 0.0, 1.0, 0.0],
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
fn dim(&self) -> usize {
|
||||
4
|
||||
}
|
||||
fn model_id(&self) -> &str {
|
||||
"stub"
|
||||
}
|
||||
}
|
||||
|
||||
fn record(id: &str, content: &str, category: &str) -> MemoryRecord {
|
||||
MemoryRecord {
|
||||
id: id.to_string(),
|
||||
category: category.to_string(),
|
||||
title: id.to_string(),
|
||||
content: content.to_string(),
|
||||
keywords: vec![],
|
||||
scope: "global".to_string(),
|
||||
timestamp: "0".to_string(),
|
||||
source: "test".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn open(dir: &Path) -> MemoryIndex {
|
||||
MemoryIndex::open(dir, 4, "stub", Arc::new(StubEmbedder)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_then_search_finds_record() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let idx = open(tmp.path());
|
||||
idx.upsert(&record("r1", "alpha", "facts")).unwrap();
|
||||
idx.flush().unwrap();
|
||||
let hits = idx.search("alpha", 5, 0.0, None, None).unwrap();
|
||||
assert_eq!(hits.len(), 1);
|
||||
assert_eq!(hits[0].record.id, "r1");
|
||||
assert!(
|
||||
(hits[0].score - 1.0).abs() < 1e-5,
|
||||
"cosine score={}",
|
||||
hits[0].score
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_ranks_nearest_first() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let idx = open(tmp.path());
|
||||
idx.upsert(&record("a", "alpha", "facts")).unwrap();
|
||||
idx.upsert(&record("b", "beta", "facts")).unwrap();
|
||||
// threshold -1.0 includes the orthogonal (cosine 0.0) record too, so we
|
||||
// can assert ordering; a 0.0 threshold would legitimately drop it.
|
||||
let hits = idx.search("alpha", 5, -1.0, None, None).unwrap();
|
||||
assert_eq!(hits.len(), 2);
|
||||
assert_eq!(hits[0].record.id, "a");
|
||||
assert!(hits[0].score > hits[1].score);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mark_dead_excludes_from_recall() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let idx = open(tmp.path());
|
||||
idx.upsert(&record("r1", "alpha", "facts")).unwrap();
|
||||
idx.mark_dead("r1").unwrap();
|
||||
let hits = idx.search("alpha", 5, 0.0, None, None).unwrap();
|
||||
assert!(hits.is_empty(), "dead record must be excluded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn category_filter() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let idx = open(tmp.path());
|
||||
idx.upsert(&record("a", "alpha", "facts")).unwrap();
|
||||
idx.upsert(&record("b", "alpha", "experience")).unwrap();
|
||||
let hits = idx.search("alpha", 5, 0.0, Some("facts"), None).unwrap();
|
||||
assert_eq!(hits.len(), 1);
|
||||
assert_eq!(hits[0].record.id, "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopen_with_different_model_is_mismatch() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
{
|
||||
let idx = open(tmp.path());
|
||||
idx.upsert(&record("a", "alpha", "facts")).unwrap();
|
||||
idx.flush().unwrap();
|
||||
}
|
||||
let err = MemoryIndex::open(tmp.path(), 4, "other-model", Arc::new(StubEmbedder));
|
||||
assert!(matches!(err, Err(IndexError::ModelMismatch { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_ids_includes_tombstones() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let idx = open(tmp.path());
|
||||
idx.upsert(&record("a", "alpha", "facts")).unwrap();
|
||||
idx.upsert(&record("b", "beta", "facts")).unwrap();
|
||||
idx.mark_dead("b").unwrap();
|
||||
let mut ids = idx.indexed_ids().unwrap();
|
||||
ids.sort();
|
||||
// Both live and soft-deleted ids are reported (so reconciliation will not
|
||||
// re-embed and resurrect the tombstone).
|
||||
assert_eq!(ids, vec!["a".to_string(), "b".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopen_same_model_preserves_data() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
{
|
||||
let idx = open(tmp.path());
|
||||
idx.upsert(&record("a", "alpha", "facts")).unwrap();
|
||||
idx.flush().unwrap();
|
||||
}
|
||||
let idx = open(tmp.path());
|
||||
let hits = idx.search("alpha", 5, 0.0, None, None).unwrap();
|
||||
assert_eq!(hits.len(), 1);
|
||||
assert_eq!(hits[0].record.id, "a");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! strata-memory — semantic memory primitives for strata-ctl.
|
||||
//!
|
||||
//! Self-contained on purpose: it knows nothing of sessions or the GUI. It exposes
|
||||
//! a swappable [`Embedder`] trait (dense vectors only — the ratified retrieval
|
||||
//! baseline) plus an optional [`Reranker`] capability, and an [`HttpEmbedder`]
|
||||
//! backend that speaks the `vetta-embedder` (BGE-M3) HTTP contract. The later
|
||||
//! in-process Rust embedder drops in behind the same trait with no caller change.
|
||||
//!
|
||||
//! The vector index (Qdrant Edge) and the record schema land in later increments;
|
||||
//! this module fixes the embedder seam first so the spike and the production path
|
||||
//! share one interface.
|
||||
|
||||
use std::io::Read;
|
||||
use std::time::Duration;
|
||||
|
||||
pub mod workspace;
|
||||
pub use workspace::{
|
||||
ExecReport, Outcome, VectorSlot, VectorSource, VectorWorkspace, WorkspaceError,
|
||||
};
|
||||
|
||||
pub mod index;
|
||||
pub use index::{Hit, IndexError, MemoryIndex, MemoryRecord};
|
||||
|
||||
/// Default dense dimension of BGE-M3 as served by `vetta-embedder`.
|
||||
pub const BGE_M3_DIM: usize = 1024;
|
||||
|
||||
/// Errors surfaced by the embedder seam. Transport failures and contract
|
||||
/// violations are distinguished so callers can fail-open (e.g. persist a memory
|
||||
/// record and defer re-indexing when the embedder is unreachable).
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EmbedError {
|
||||
#[error("transport: {0}")]
|
||||
Transport(String),
|
||||
#[error("decode: {0}")]
|
||||
Decode(String),
|
||||
#[error("server error {status}: {body}")]
|
||||
Server { status: u16, body: String },
|
||||
#[error("unexpected response shape: {0}")]
|
||||
Shape(String),
|
||||
}
|
||||
|
||||
/// Dense embedding provider. One embedder for all memory content; specialization
|
||||
/// happens above the index (directive packs), not by swapping models per use.
|
||||
pub trait Embedder: Send + Sync {
|
||||
/// Return one L2-normalized dense vector per input text, in order.
|
||||
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, EmbedError>;
|
||||
|
||||
/// Vector dimension this embedder emits (used to size + validate the index).
|
||||
fn dim(&self) -> usize;
|
||||
|
||||
/// Stable model identifier. Persisted alongside the index so that switching
|
||||
/// embedders (or quantization) is detectable and forces a rebuild instead of
|
||||
/// silently mixing incompatible vectors.
|
||||
fn model_id(&self) -> &str;
|
||||
}
|
||||
|
||||
/// A single reranked document: original input index + relevance score. Scores are
|
||||
/// raw cross-encoder logits; only their ordering is meaningful.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Reranked {
|
||||
pub index: usize,
|
||||
pub score: f64,
|
||||
}
|
||||
|
||||
/// Optional second-stage capability. Kept as a separate trait (not a method on
|
||||
/// [`Embedder`]) so an embedder without a reranker still satisfies the core
|
||||
/// interface, and consumers probe for reranking at runtime.
|
||||
pub trait Reranker: Send + Sync {
|
||||
fn rerank(&self, query: &str, docs: &[&str], top_n: usize)
|
||||
-> Result<Vec<Reranked>, EmbedError>;
|
||||
}
|
||||
|
||||
/// [`Embedder`] + [`Reranker`] backend over the `vetta-embedder` HTTP contract:
|
||||
/// `POST /embed {texts:[...]} -> {embeddings:[[...]]}` and
|
||||
/// `POST /rerank {query,documents,top_n} -> {results:[{index,score,document}]}`.
|
||||
///
|
||||
/// Synchronous by design (a library must not dictate an async runtime); strata-ctl
|
||||
/// calls it from `tokio::task::spawn_blocking`.
|
||||
pub struct HttpEmbedder {
|
||||
base_url: String,
|
||||
model_id: String,
|
||||
dim: usize,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl HttpEmbedder {
|
||||
/// `base_url` is e.g. `http://192.168.50.18:8091` (supplied by the caller from
|
||||
/// the DB config — deliberately not hardcoded here). `model_id` tags the index.
|
||||
pub fn new(base_url: impl Into<String>, model_id: impl Into<String>, dim: usize) -> Self {
|
||||
Self {
|
||||
base_url: base_url.into(),
|
||||
model_id: model_id.into(),
|
||||
dim,
|
||||
timeout: Duration::from_secs(8),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.timeout = timeout;
|
||||
self
|
||||
}
|
||||
|
||||
fn agent(&self) -> ureq::Agent {
|
||||
ureq::Agent::config_builder()
|
||||
.timeout_global(Some(self.timeout))
|
||||
.build()
|
||||
.new_agent()
|
||||
}
|
||||
|
||||
fn post_json(
|
||||
&self,
|
||||
path: &str,
|
||||
body: &serde_json::Value,
|
||||
) -> Result<serde_json::Value, EmbedError> {
|
||||
let url = format!("{}{}", self.base_url.trim_end_matches('/'), path);
|
||||
let mut resp = self
|
||||
.agent()
|
||||
.post(&url)
|
||||
.send_json(body)
|
||||
.map_err(|e| EmbedError::Transport(e.to_string()))?;
|
||||
let status = resp.status().as_u16();
|
||||
let mut buf = Vec::new();
|
||||
resp.body_mut()
|
||||
.as_reader()
|
||||
.read_to_end(&mut buf)
|
||||
.map_err(|e| EmbedError::Transport(e.to_string()))?;
|
||||
if !(200..300).contains(&status) {
|
||||
let body = String::from_utf8_lossy(&buf).chars().take(512).collect();
|
||||
return Err(EmbedError::Server { status, body });
|
||||
}
|
||||
serde_json::from_slice(&buf).map_err(|e| EmbedError::Decode(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `{"embeddings": [[f32, ...], ...]}`. Public-shape tolerant: reads numbers
|
||||
/// via `as_f64` and narrows to f32.
|
||||
fn parse_embeddings(v: &serde_json::Value) -> Result<Vec<Vec<f32>>, EmbedError> {
|
||||
let arr = v
|
||||
.get("embeddings")
|
||||
.and_then(|e| e.as_array())
|
||||
.ok_or_else(|| EmbedError::Shape("missing 'embeddings' array".into()))?;
|
||||
arr.iter()
|
||||
.map(|row| {
|
||||
row.as_array()
|
||||
.map(|r| {
|
||||
r.iter()
|
||||
.filter_map(|x| x.as_f64().map(|f| f as f32))
|
||||
.collect::<Vec<f32>>()
|
||||
})
|
||||
.ok_or_else(|| EmbedError::Shape("embedding row is not an array".into()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Parse `{"results": [{"index": n, "score": s}, ...]}` into [`Reranked`].
|
||||
fn parse_rerank(v: &serde_json::Value) -> Result<Vec<Reranked>, EmbedError> {
|
||||
let arr = v
|
||||
.get("results")
|
||||
.and_then(|e| e.as_array())
|
||||
.ok_or_else(|| EmbedError::Shape("missing 'results' array".into()))?;
|
||||
arr.iter()
|
||||
.map(|r| {
|
||||
let index = r
|
||||
.get("index")
|
||||
.and_then(|i| i.as_u64())
|
||||
.ok_or_else(|| EmbedError::Shape("result missing 'index'".into()))?
|
||||
as usize;
|
||||
let score = r
|
||||
.get("score")
|
||||
.and_then(|s| s.as_f64())
|
||||
.ok_or_else(|| EmbedError::Shape("result missing 'score'".into()))?;
|
||||
Ok(Reranked { index, score })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Embedder for HttpEmbedder {
|
||||
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, EmbedError> {
|
||||
let body = serde_json::json!({ "texts": texts });
|
||||
let v = self.post_json("/embed", &body)?;
|
||||
let out = parse_embeddings(&v)?;
|
||||
if out.len() != texts.len() {
|
||||
return Err(EmbedError::Shape(format!(
|
||||
"expected {} vectors, got {}",
|
||||
texts.len(),
|
||||
out.len()
|
||||
)));
|
||||
}
|
||||
for row in &out {
|
||||
if row.len() != self.dim {
|
||||
return Err(EmbedError::Shape(format!(
|
||||
"expected dim {}, got {}",
|
||||
self.dim,
|
||||
row.len()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn dim(&self) -> usize {
|
||||
self.dim
|
||||
}
|
||||
|
||||
fn model_id(&self) -> &str {
|
||||
&self.model_id
|
||||
}
|
||||
}
|
||||
|
||||
impl Reranker for HttpEmbedder {
|
||||
fn rerank(
|
||||
&self,
|
||||
query: &str,
|
||||
docs: &[&str],
|
||||
top_n: usize,
|
||||
) -> Result<Vec<Reranked>, EmbedError> {
|
||||
let body = serde_json::json!({ "query": query, "documents": docs, "top_n": top_n });
|
||||
let v = self.post_json("/rerank", &body)?;
|
||||
parse_rerank(&v)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_embeddings_reads_dense_rows() {
|
||||
let json = serde_json::json!({"embeddings": [[0.1, 0.2, 0.3], [-0.4, 0.5, 0.6]]});
|
||||
let out = parse_embeddings(&json).unwrap();
|
||||
assert_eq!(out.len(), 2);
|
||||
assert_eq!(out[0].len(), 3);
|
||||
assert!((out[0][0] - 0.1).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_embeddings_rejects_missing_key() {
|
||||
let json = serde_json::json!({"error": "no texts provided"});
|
||||
assert!(matches!(parse_embeddings(&json), Err(EmbedError::Shape(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_rerank_preserves_order_and_index() {
|
||||
// Shape captured live from :8091/rerank.
|
||||
let json = serde_json::json!({
|
||||
"query": "come si configura il token MCP",
|
||||
"results": [
|
||||
{"index": 1, "score": -1.708251, "document": "mcp token"},
|
||||
{"index": 0, "score": -10.783061, "document": "gatto"},
|
||||
{"index": 2, "score": -11.032022, "document": "carbonara"}
|
||||
]
|
||||
});
|
||||
let out = parse_rerank(&json).unwrap();
|
||||
assert_eq!(out[0].index, 1); // most relevant first
|
||||
assert_eq!(out[1].index, 0);
|
||||
assert_eq!(out[2].index, 2);
|
||||
assert!(out[0].score > out[1].score);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dim_is_reported_and_used_for_validation() {
|
||||
let e = HttpEmbedder::new("http://127.0.0.1:9", "bge-m3-q8", BGE_M3_DIM);
|
||||
assert_eq!(e.dim(), 1024);
|
||||
assert_eq!(e.model_id(), "bge-m3-q8");
|
||||
}
|
||||
|
||||
/// Hits the real Altair instance; run explicitly with the LAN reachable.
|
||||
/// `cargo test -- --ignored` — mirrors the repo's convention for live checks.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn live_embed_altair_returns_unit_norm_dense() {
|
||||
let e = HttpEmbedder::new("http://192.168.50.18:8091", "bge-m3-q8", BGE_M3_DIM);
|
||||
let v = e.embed(&["Il gatto nero salta sul tavolo"]).unwrap();
|
||||
assert_eq!(v[0].len(), 1024);
|
||||
let norm: f32 = v[0].iter().map(|x| x * x).sum::<f32>().sqrt();
|
||||
assert!(
|
||||
(norm - 1.0).abs() < 1e-3,
|
||||
"expected L2-normalized, got norm {norm}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,804 @@
|
||||
//! Symbolic vector workspace — an RPN calculator over embeddings with 16
|
||||
//! persistent per-session slots `$VEC[0..15]`.
|
||||
//!
|
||||
//! Design principle (Federico): vectors are handled SYMBOLICALLY. The full
|
||||
//! 1024-float arrays live server-side (in the slots / the index); what reaches
|
||||
//! the model is only references (`$VEC[n]`), scalar metrics (COS/DOT/NORM),
|
||||
//! slot metadata, and at most an 8-value preview. [`ExecReport`] carries an
|
||||
//! [`Outcome`] that structurally cannot contain a full vector, so the rendering
|
||||
//! path can never dump the array into context.
|
||||
//!
|
||||
//! Adapted from our own Iris `vector_workspace` (RPN "Vera Core"), focused on the
|
||||
//! vector algebra; the scientific-calculator extras (trig/log/HP.X bridge) are
|
||||
//! intentionally trimmed. The vector primitives are reimplemented here (trivial
|
||||
//! f32 ops) so the crate stays self-contained.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{EmbedError, Embedder};
|
||||
|
||||
/// Number of persistent slots per session (`$VEC[0]..$VEC[15]`).
|
||||
pub const VECTOR_SLOT_COUNT: usize = 16;
|
||||
/// Max floats shown when previewing a vector result (never the full array).
|
||||
const PREVIEW_LEN: usize = 8;
|
||||
|
||||
/// Provenance of a stored vector.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum VectorSource {
|
||||
TextEmbedding,
|
||||
Copied,
|
||||
Derived,
|
||||
}
|
||||
|
||||
impl VectorSource {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
VectorSource::TextEmbedding => "TextEmbedding",
|
||||
VectorSource::Copied => "Copied",
|
||||
VectorSource::Derived => "Derived",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One persistent slot. The `vector` is the real data, kept server-side; it is
|
||||
/// serialized only for DB persistence (strata-ctl owns the Store), never for the
|
||||
/// model-facing report.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VectorSlot {
|
||||
pub dims: usize,
|
||||
pub label: Option<String>,
|
||||
pub source: VectorSource,
|
||||
pub updated_at: String,
|
||||
pub vector: Vec<f32>,
|
||||
}
|
||||
|
||||
/// The per-session workspace. Serializable so strata-ctl can persist it in the DB.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct VectorWorkspace {
|
||||
pub slots: [Option<VectorSlot>; VECTOR_SLOT_COUNT],
|
||||
}
|
||||
|
||||
impl Default for VectorWorkspace {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors from lexing/evaluating a program or resolving a slot reference.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum WorkspaceError {
|
||||
#[error("parse: {0}")]
|
||||
Parse(String),
|
||||
#[error("stack: {0}")]
|
||||
Stack(String),
|
||||
#[error("type: {0}")]
|
||||
Type(String),
|
||||
#[error("slot: {0}")]
|
||||
Slot(String),
|
||||
#[error("dims: {0}")]
|
||||
Dims(String),
|
||||
#[error(transparent)]
|
||||
Embed(#[from] EmbedError),
|
||||
}
|
||||
|
||||
/// A model-facing result. Deliberately has NO full-vector variant: a vector is
|
||||
/// summarized as `dims` + an ≤8-value `preview`, so the array cannot leak into
|
||||
/// context through the report.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Outcome {
|
||||
Scalar(f64),
|
||||
Text(String),
|
||||
Vector { dims: usize, preview: String },
|
||||
}
|
||||
|
||||
/// Result of executing a program: the final stack value (summarized), the slots
|
||||
/// touched, and human-readable notes (INFO/LIST).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ExecReport {
|
||||
pub result: Option<Outcome>,
|
||||
pub touched_slots: Vec<usize>,
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
// Internal runtime value: during evaluation the stack DOES hold full vectors;
|
||||
// they are summarized into an Outcome only when building the report.
|
||||
#[derive(Debug, Clone)]
|
||||
enum Value {
|
||||
Text(String),
|
||||
Scalar(f64),
|
||||
Vector(Vec<f32>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum Token {
|
||||
Word(String),
|
||||
Quoted(String),
|
||||
}
|
||||
|
||||
impl VectorWorkspace {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
slots: std::array::from_fn(|_| None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve a symbolic reference (`$VEC[n]`) to its vector, server-side. This
|
||||
/// is the bridge used by search: the model passes `"$VEC[0]"`, the framework
|
||||
/// resolves it here and feeds the index — the floats never enter context.
|
||||
pub fn resolve(&self, reference: &str) -> Result<Vec<f32>, WorkspaceError> {
|
||||
let idx = parse_slot_ref(reference)?;
|
||||
self.slots[idx]
|
||||
.as_ref()
|
||||
.map(|s| s.vector.clone())
|
||||
.ok_or_else(|| WorkspaceError::Slot(format!("$VEC[{idx}] is empty")))
|
||||
}
|
||||
|
||||
/// Execute an RPN program. `embedder` backs the `EMB` op.
|
||||
pub fn execute(
|
||||
&mut self,
|
||||
program: &str,
|
||||
embedder: &dyn Embedder,
|
||||
) -> Result<ExecReport, WorkspaceError> {
|
||||
let tokens = lex(program)?;
|
||||
let mut stack: Vec<Value> = Vec::new();
|
||||
let mut touched: Vec<usize> = Vec::new();
|
||||
let mut notes: Vec<String> = Vec::new();
|
||||
let mut i = 0;
|
||||
|
||||
while i < tokens.len() {
|
||||
match &tokens[i] {
|
||||
Token::Quoted(text) => {
|
||||
stack.push(Value::Text(text.clone()));
|
||||
i += 1;
|
||||
}
|
||||
Token::Word(word) => {
|
||||
if let Ok(v) = word.parse::<f64>() {
|
||||
stack.push(Value::Scalar(v));
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let op = word.to_ascii_uppercase();
|
||||
match op.as_str() {
|
||||
// ── stack ──
|
||||
"DUP" => {
|
||||
let top = stack.last().cloned().ok_or_else(|| under("DUP"))?;
|
||||
stack.push(top);
|
||||
i += 1;
|
||||
}
|
||||
"DROP" => {
|
||||
stack.pop().ok_or_else(|| under("DROP"))?;
|
||||
i += 1;
|
||||
}
|
||||
"SWAP" => {
|
||||
need(&stack, 2, "SWAP")?;
|
||||
let n = stack.len();
|
||||
stack.swap(n - 1, n - 2);
|
||||
i += 1;
|
||||
}
|
||||
"OVER" => {
|
||||
need(&stack, 2, "OVER")?;
|
||||
let v = stack[stack.len() - 2].clone();
|
||||
stack.push(v);
|
||||
i += 1;
|
||||
}
|
||||
"ROT" => {
|
||||
need(&stack, 3, "ROT")?;
|
||||
let a = stack.pop().unwrap();
|
||||
let b = stack.pop().unwrap();
|
||||
let c = stack.pop().unwrap();
|
||||
stack.push(b);
|
||||
stack.push(a);
|
||||
stack.push(c);
|
||||
i += 1;
|
||||
}
|
||||
"CLEAR" => {
|
||||
stack.clear();
|
||||
i += 1;
|
||||
}
|
||||
// ── scalar ──
|
||||
"+" | "-" | "*" | "/" | "POW" | "^" | "GT" | ">" | "LT" | "<" | "EQ"
|
||||
| "==" => {
|
||||
let b = pop_scalar(&mut stack)?;
|
||||
let a = pop_scalar(&mut stack)?;
|
||||
let r = match op.as_str() {
|
||||
"+" => a + b,
|
||||
"-" => a - b,
|
||||
"*" => a * b,
|
||||
"/" => {
|
||||
if b == 0.0 {
|
||||
return Err(WorkspaceError::Stack(
|
||||
"division by zero".into(),
|
||||
));
|
||||
}
|
||||
a / b
|
||||
}
|
||||
"POW" | "^" => a.powf(b),
|
||||
"GT" | ">" => bool_num(a > b),
|
||||
"LT" | "<" => bool_num(a < b),
|
||||
_ => bool_num((a - b).abs() < 1e-9),
|
||||
};
|
||||
stack.push(Value::Scalar(r));
|
||||
i += 1;
|
||||
}
|
||||
"SQRT" | "ABS" | "NEG" | "NOT" | "!" => {
|
||||
let a = pop_scalar(&mut stack)?;
|
||||
let r = match op.as_str() {
|
||||
"SQRT" => a.sqrt(),
|
||||
"ABS" => a.abs(),
|
||||
"NEG" => -a,
|
||||
_ => bool_num(a == 0.0),
|
||||
};
|
||||
stack.push(Value::Scalar(r));
|
||||
i += 1;
|
||||
}
|
||||
// ── embeddings / slots ──
|
||||
"EMB" => {
|
||||
let text = pop_text(&mut stack)?;
|
||||
let mut v = embedder.embed(&[text.as_str()])?;
|
||||
let vec = v.pop().ok_or_else(|| {
|
||||
WorkspaceError::Embed(EmbedError::Shape("empty".into()))
|
||||
})?;
|
||||
stack.push(Value::Vector(vec));
|
||||
i += 1;
|
||||
}
|
||||
"RCL" => {
|
||||
let idx = parse_slot_arg(tokens.get(i + 1))?;
|
||||
let stored = self.slots[idx].as_ref().ok_or_else(|| {
|
||||
WorkspaceError::Slot(format!("$VEC[{idx}] is empty"))
|
||||
})?;
|
||||
stack.push(Value::Vector(stored.vector.clone()));
|
||||
i += 2;
|
||||
}
|
||||
"STO" => {
|
||||
let idx = parse_slot_arg(tokens.get(i + 1))?;
|
||||
let vec = pop_vector(&mut stack)?;
|
||||
let label = self.slots[idx].as_ref().and_then(|s| s.label.clone());
|
||||
self.slots[idx] = Some(VectorSlot {
|
||||
dims: vec.len(),
|
||||
label,
|
||||
source: VectorSource::Copied,
|
||||
updated_at: now_stamp(),
|
||||
vector: vec,
|
||||
});
|
||||
touch(&mut touched, idx);
|
||||
i += 2;
|
||||
}
|
||||
"CLR" => {
|
||||
let idx = parse_slot_arg(tokens.get(i + 1))?;
|
||||
self.slots[idx] = None;
|
||||
touch(&mut touched, idx);
|
||||
i += 2;
|
||||
}
|
||||
"LABEL" => {
|
||||
let idx = parse_slot_arg(tokens.get(i + 1))?;
|
||||
let label = parse_label_arg(tokens.get(i + 2))?;
|
||||
let entry = self.slots[idx].as_mut().ok_or_else(|| {
|
||||
WorkspaceError::Slot(format!("cannot label empty $VEC[{idx}]"))
|
||||
})?;
|
||||
entry.label = Some(label);
|
||||
entry.updated_at = now_stamp();
|
||||
touch(&mut touched, idx);
|
||||
i += 3;
|
||||
}
|
||||
"INFO" => {
|
||||
let idx = parse_slot_arg(tokens.get(i + 1))?;
|
||||
notes.push(self.slot_line(idx));
|
||||
i += 2;
|
||||
}
|
||||
"LIST" => {
|
||||
notes.push(self.list());
|
||||
i += 1;
|
||||
}
|
||||
// ── vector algebra ──
|
||||
"V+" | "V-" | "AVG" | "WAVG" => {
|
||||
let w = if op == "WAVG" {
|
||||
Some(pop_scalar(&mut stack)? as f32)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let rhs = pop_vector(&mut stack)?;
|
||||
let lhs = pop_vector(&mut stack)?;
|
||||
let r = match op.as_str() {
|
||||
"V+" => v_add(&lhs, &rhs)?,
|
||||
"V-" => v_sub(&lhs, &rhs)?,
|
||||
"AVG" => v_scale(&v_add(&lhs, &rhs)?, 0.5),
|
||||
_ => v_wavg(&lhs, &rhs, w.unwrap()),
|
||||
};
|
||||
stack.push(Value::Vector(r));
|
||||
i += 1;
|
||||
}
|
||||
"UNIT" => {
|
||||
let v = pop_vector(&mut stack)?;
|
||||
stack.push(Value::Vector(v_unit(&v)?));
|
||||
i += 1;
|
||||
}
|
||||
"SCALE" => {
|
||||
let top = stack.pop().ok_or_else(|| under("SCALE"))?;
|
||||
let second = stack.pop().ok_or_else(|| under("SCALE"))?;
|
||||
let (vec, s) = match (second, top) {
|
||||
(Value::Vector(v), Value::Scalar(s)) => (v, s as f32),
|
||||
(Value::Scalar(s), Value::Vector(v)) => (v, s as f32),
|
||||
_ => {
|
||||
return Err(WorkspaceError::Type(
|
||||
"SCALE expects one vector and one scalar".into(),
|
||||
))
|
||||
}
|
||||
};
|
||||
stack.push(Value::Vector(v_scale(&vec, s)));
|
||||
i += 1;
|
||||
}
|
||||
"COS" | "DOT" | "DIST" | "PROJ" => {
|
||||
let rhs = pop_vector(&mut stack)?;
|
||||
let lhs = pop_vector(&mut stack)?;
|
||||
let r = match op.as_str() {
|
||||
"COS" => v_cosine(&lhs, &rhs)? as f64,
|
||||
"DOT" => v_dot(&lhs, &rhs)? as f64,
|
||||
"DIST" => 1.0 - v_cosine(&lhs, &rhs)? as f64,
|
||||
_ => v_proj(&lhs, &rhs)? as f64,
|
||||
};
|
||||
stack.push(Value::Scalar(r));
|
||||
i += 1;
|
||||
}
|
||||
"NORM" => {
|
||||
let v = pop_vector(&mut stack)?;
|
||||
stack.push(Value::Scalar(v_norm(&v) as f64));
|
||||
i += 1;
|
||||
}
|
||||
_ => {
|
||||
return Err(WorkspaceError::Parse(format!("unknown token '{word}'")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let result = stack.last().map(summarize);
|
||||
Ok(ExecReport {
|
||||
result,
|
||||
touched_slots: touched,
|
||||
notes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Model-facing rendering: scalars, text, slot metadata, ≤8-value previews.
|
||||
/// Never the full vector.
|
||||
pub fn render(&self, report: &ExecReport) -> String {
|
||||
let mut lines = vec!["VectorWorkspace executed successfully.".to_string()];
|
||||
match &report.result {
|
||||
Some(Outcome::Scalar(v)) => lines.push(format!("Final result: scalar {v:.6}")),
|
||||
Some(Outcome::Text(t)) => lines.push(format!("Final result: text \"{t}\"")),
|
||||
Some(Outcome::Vector { dims, preview }) => {
|
||||
lines.push(format!("Final result: vector[{dims}] = [{preview}]"))
|
||||
}
|
||||
None => lines.push("Final result: no stack value.".to_string()),
|
||||
}
|
||||
if !report.touched_slots.is_empty() {
|
||||
lines.push("Touched slots:".to_string());
|
||||
for idx in &report.touched_slots {
|
||||
lines.push(self.slot_line(*idx));
|
||||
}
|
||||
}
|
||||
if !report.notes.is_empty() {
|
||||
lines.push("Notes:".to_string());
|
||||
lines.extend(report.notes.iter().cloned());
|
||||
}
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
/// Occupied-slot listing (metadata only).
|
||||
pub fn list(&self) -> String {
|
||||
let occupied: Vec<String> = self
|
||||
.slots
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, s)| s.as_ref().map(|_| self.slot_line(idx)))
|
||||
.collect();
|
||||
if occupied.is_empty() {
|
||||
"Occupied slots: none".to_string()
|
||||
} else {
|
||||
format!("Occupied slots:\n{}", occupied.join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
fn slot_line(&self, idx: usize) -> String {
|
||||
match &self.slots[idx] {
|
||||
Some(s) => {
|
||||
let label = s
|
||||
.label
|
||||
.as_ref()
|
||||
.map(|l| format!(" label=\"{l}\""))
|
||||
.unwrap_or_default();
|
||||
format!(
|
||||
"- $VEC[{idx}]: occupied=true dims={} source={}{} updated_at={}",
|
||||
s.dims,
|
||||
s.source.as_str(),
|
||||
label,
|
||||
s.updated_at
|
||||
)
|
||||
}
|
||||
None => format!("- $VEC[{idx}]: occupied=false"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── summarization / preview (the symbolic boundary) ──
|
||||
|
||||
fn summarize(v: &Value) -> Outcome {
|
||||
match v {
|
||||
Value::Scalar(s) => Outcome::Scalar(*s),
|
||||
Value::Text(t) => Outcome::Text(t.clone()),
|
||||
Value::Vector(vec) => Outcome::Vector {
|
||||
dims: vec.len(),
|
||||
preview: preview_vector(vec),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_vector(vec: &[f32]) -> String {
|
||||
let head: Vec<String> = vec
|
||||
.iter()
|
||||
.take(PREVIEW_LEN)
|
||||
.map(|v| format!("{v:.4}"))
|
||||
.collect();
|
||||
if vec.len() > PREVIEW_LEN {
|
||||
format!("{}, ...", head.join(", "))
|
||||
} else {
|
||||
head.join(", ")
|
||||
}
|
||||
}
|
||||
|
||||
// ── vector primitives (reimplemented, self-contained) ──
|
||||
|
||||
fn check_dims(a: &[f32], b: &[f32]) -> Result<(), WorkspaceError> {
|
||||
if a.len() != b.len() {
|
||||
return Err(WorkspaceError::Dims(format!("{} vs {}", a.len(), b.len())));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn v_add(a: &[f32], b: &[f32]) -> Result<Vec<f32>, WorkspaceError> {
|
||||
check_dims(a, b)?;
|
||||
Ok(a.iter().zip(b).map(|(x, y)| x + y).collect())
|
||||
}
|
||||
|
||||
fn v_sub(a: &[f32], b: &[f32]) -> Result<Vec<f32>, WorkspaceError> {
|
||||
check_dims(a, b)?;
|
||||
Ok(a.iter().zip(b).map(|(x, y)| x - y).collect())
|
||||
}
|
||||
|
||||
fn v_scale(a: &[f32], s: f32) -> Vec<f32> {
|
||||
a.iter().map(|x| x * s).collect()
|
||||
}
|
||||
|
||||
/// Linear interpolation: `lhs*(1-w) + rhs*w`.
|
||||
fn v_wavg(a: &[f32], b: &[f32], w: f32) -> Vec<f32> {
|
||||
a.iter()
|
||||
.zip(b)
|
||||
.map(|(x, y)| x * (1.0 - w) + y * w)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn v_dot(a: &[f32], b: &[f32]) -> Result<f32, WorkspaceError> {
|
||||
check_dims(a, b)?;
|
||||
Ok(a.iter().zip(b).map(|(x, y)| x * y).sum())
|
||||
}
|
||||
|
||||
fn v_norm(a: &[f32]) -> f32 {
|
||||
a.iter().map(|x| x * x).sum::<f32>().sqrt()
|
||||
}
|
||||
|
||||
fn v_unit(a: &[f32]) -> Result<Vec<f32>, WorkspaceError> {
|
||||
let n = v_norm(a);
|
||||
if n <= 1e-12 {
|
||||
return Err(WorkspaceError::Dims(
|
||||
"cannot normalize a zero vector".into(),
|
||||
));
|
||||
}
|
||||
Ok(v_scale(a, 1.0 / n))
|
||||
}
|
||||
|
||||
fn v_cosine(a: &[f32], b: &[f32]) -> Result<f32, WorkspaceError> {
|
||||
check_dims(a, b)?;
|
||||
let na = v_norm(a);
|
||||
let nb = v_norm(b);
|
||||
if na <= 1e-12 || nb <= 1e-12 {
|
||||
return Err(WorkspaceError::Dims("cosine with a zero vector".into()));
|
||||
}
|
||||
Ok(v_dot(a, b)? / (na * nb))
|
||||
}
|
||||
|
||||
/// Scalar projection of `a` onto `b`: `dot(a,b)/|b|`.
|
||||
fn v_proj(a: &[f32], b: &[f32]) -> Result<f32, WorkspaceError> {
|
||||
check_dims(a, b)?;
|
||||
let nb = v_norm(b);
|
||||
if nb <= 1e-12 {
|
||||
return Err(WorkspaceError::Dims("projection onto a zero vector".into()));
|
||||
}
|
||||
Ok(v_dot(a, b)? / nb)
|
||||
}
|
||||
|
||||
// ── lexing / parsing helpers ──
|
||||
|
||||
fn lex(input: &str) -> Result<Vec<Token>, WorkspaceError> {
|
||||
let chars: Vec<char> = input.chars().collect();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
if chars[i].is_whitespace() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if chars[i] == '"' {
|
||||
i += 1;
|
||||
let mut s = String::new();
|
||||
while i < chars.len() && chars[i] != '"' {
|
||||
s.push(chars[i]);
|
||||
i += 1;
|
||||
}
|
||||
if i >= chars.len() {
|
||||
return Err(WorkspaceError::Parse("unterminated quoted string".into()));
|
||||
}
|
||||
i += 1; // closing quote
|
||||
out.push(Token::Quoted(s));
|
||||
continue;
|
||||
}
|
||||
let start = i;
|
||||
while i < chars.len() && !chars[i].is_whitespace() {
|
||||
i += 1;
|
||||
}
|
||||
out.push(Token::Word(chars[start..i].iter().collect()));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn parse_slot_ref(raw: &str) -> Result<usize, WorkspaceError> {
|
||||
let upper = raw.to_ascii_uppercase();
|
||||
let inner = upper
|
||||
.strip_prefix("$VEC[")
|
||||
.and_then(|s| s.strip_suffix(']'))
|
||||
.ok_or_else(|| {
|
||||
WorkspaceError::Parse(format!("invalid slot reference '{raw}', expected $VEC[n]"))
|
||||
})?;
|
||||
let idx: usize = inner
|
||||
.parse()
|
||||
.map_err(|_| WorkspaceError::Parse(format!("invalid slot index in '{raw}'")))?;
|
||||
if idx >= VECTOR_SLOT_COUNT {
|
||||
return Err(WorkspaceError::Slot(format!(
|
||||
"$VEC[{idx}] out of range (0..{})",
|
||||
VECTOR_SLOT_COUNT - 1
|
||||
)));
|
||||
}
|
||||
Ok(idx)
|
||||
}
|
||||
|
||||
fn parse_slot_arg(token: Option<&Token>) -> Result<usize, WorkspaceError> {
|
||||
match token {
|
||||
Some(Token::Word(w)) => parse_slot_ref(w),
|
||||
Some(Token::Quoted(_)) => Err(WorkspaceError::Parse(
|
||||
"expected $VEC[n], got quoted text".into(),
|
||||
)),
|
||||
None => Err(WorkspaceError::Parse("missing slot reference".into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_label_arg(token: Option<&Token>) -> Result<String, WorkspaceError> {
|
||||
match token {
|
||||
Some(Token::Quoted(t)) | Some(Token::Word(t)) => Ok(t.clone()),
|
||||
None => Err(WorkspaceError::Parse("missing label text".into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn pop_text(stack: &mut Vec<Value>) -> Result<String, WorkspaceError> {
|
||||
match stack.pop() {
|
||||
Some(Value::Text(t)) => Ok(t),
|
||||
Some(_) => Err(WorkspaceError::Type("expected text".into())),
|
||||
None => Err(under("text")),
|
||||
}
|
||||
}
|
||||
|
||||
fn pop_vector(stack: &mut Vec<Value>) -> Result<Vec<f32>, WorkspaceError> {
|
||||
match stack.pop() {
|
||||
Some(Value::Vector(v)) => Ok(v),
|
||||
Some(_) => Err(WorkspaceError::Type("expected vector".into())),
|
||||
None => Err(under("vector")),
|
||||
}
|
||||
}
|
||||
|
||||
fn pop_scalar(stack: &mut Vec<Value>) -> Result<f64, WorkspaceError> {
|
||||
match stack.pop() {
|
||||
Some(Value::Scalar(v)) => Ok(v),
|
||||
Some(_) => Err(WorkspaceError::Type("expected scalar".into())),
|
||||
None => Err(under("scalar")),
|
||||
}
|
||||
}
|
||||
|
||||
fn under(op: &str) -> WorkspaceError {
|
||||
WorkspaceError::Stack(format!("underflow on {op}"))
|
||||
}
|
||||
|
||||
fn need(stack: &[Value], n: usize, op: &str) -> Result<(), WorkspaceError> {
|
||||
if stack.len() < n {
|
||||
return Err(under(op));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn bool_num(b: bool) -> f64 {
|
||||
if b {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
fn touch(touched: &mut Vec<usize>, idx: usize) {
|
||||
if !touched.contains(&idx) {
|
||||
touched.push(idx);
|
||||
}
|
||||
}
|
||||
|
||||
fn now_stamp() -> String {
|
||||
// No chrono dependency in this crate: a stable UTC timestamp from SystemTime.
|
||||
match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
|
||||
Ok(d) => format!("{}", d.as_secs()),
|
||||
Err(_) => "0".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Deterministic embedder for hermetic tests: maps text to a small vector.
|
||||
struct StubEmbedder;
|
||||
impl Embedder for StubEmbedder {
|
||||
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, EmbedError> {
|
||||
Ok(texts
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let n = t.len() as f32;
|
||||
vec![n, n * 2.0, n * 3.0, 0.0]
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
fn dim(&self) -> usize {
|
||||
4
|
||||
}
|
||||
fn model_id(&self) -> &str {
|
||||
"stub"
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slot_ref_parse_and_range() {
|
||||
assert_eq!(parse_slot_ref("$VEC[3]").unwrap(), 3);
|
||||
assert_eq!(parse_slot_ref("$vec[15]").unwrap(), 15);
|
||||
assert!(parse_slot_ref("$VEC[16]").is_err());
|
||||
assert!(parse_slot_ref("VEC[0]").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lex_preserves_quoted_strings() {
|
||||
let t = lex("\"hello world\" EMB STO $VEC[0]").unwrap();
|
||||
assert!(matches!(&t[0], Token::Quoted(s) if s == "hello world"));
|
||||
assert!(matches!(&t[1], Token::Word(s) if s == "EMB"));
|
||||
assert!(matches!(&t[3], Token::Word(s) if s == "$VEC[0]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emb_sto_rcl_cos_roundtrip() {
|
||||
let mut ws = VectorWorkspace::new();
|
||||
let e = StubEmbedder;
|
||||
// "ab" -> [2,4,6,0]; "abcd" -> [4,8,12,0] (parallel => cosine 1.0)
|
||||
ws.execute("\"ab\" EMB STO $VEC[0]", &e).unwrap();
|
||||
let rep = ws.execute("\"abcd\" EMB RCL $VEC[0] COS", &e).unwrap();
|
||||
match rep.result {
|
||||
Some(Outcome::Scalar(s)) => assert!((s - 1.0).abs() < 1e-5, "cos={s}"),
|
||||
other => panic!("expected scalar cosine, got {other:?}"),
|
||||
}
|
||||
assert_eq!(ws.resolve("$VEC[0]").unwrap().len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unit_normalizes_to_one() {
|
||||
let mut ws = VectorWorkspace::new();
|
||||
let rep = ws.execute("\"abc\" EMB UNIT NORM", &StubEmbedder).unwrap();
|
||||
match rep.result {
|
||||
Some(Outcome::Scalar(s)) => assert!((s - 1.0).abs() < 1e-5),
|
||||
other => panic!("expected norm 1, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn report_never_leaks_full_vector() {
|
||||
let mut ws = VectorWorkspace::new();
|
||||
// 4-dim stub vector: preview shows all 4 (<=8). Use a longer one via SCALE? dims stay 4.
|
||||
let rep = ws.execute("\"abc\" EMB", &StubEmbedder).unwrap();
|
||||
match &rep.result {
|
||||
Some(Outcome::Vector { dims, preview }) => {
|
||||
assert_eq!(*dims, 4);
|
||||
// preview is a short string, not the serialized array
|
||||
assert!(preview.split(',').count() <= PREVIEW_LEN);
|
||||
}
|
||||
other => panic!("expected vector outcome, got {other:?}"),
|
||||
}
|
||||
let rendered = ws.render(&rep);
|
||||
assert!(rendered.contains("vector[4]"));
|
||||
// The rendered report must not contain a JSON-style full array of the vector.
|
||||
assert!(!rendered.contains("[3.0, 6.0, 9.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_caps_at_eight() {
|
||||
let long: Vec<f32> = (0..1024).map(|i| i as f32).collect();
|
||||
let p = preview_vector(&long);
|
||||
assert!(p.ends_with("..."));
|
||||
assert_eq!(p.trim_end_matches(", ...").split(',').count(), PREVIEW_LEN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dim_mismatch_is_error() {
|
||||
assert!(v_add(&[1.0, 2.0], &[1.0]).is_err());
|
||||
assert!(v_cosine(&[1.0, 2.0], &[1.0]).is_err());
|
||||
assert!(v_unit(&[0.0, 0.0]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn label_and_list_metadata_only() {
|
||||
let mut ws = VectorWorkspace::new();
|
||||
ws.execute(
|
||||
"\"ab\" EMB STO $VEC[0] LABEL $VEC[0] \"gatto\"",
|
||||
&StubEmbedder,
|
||||
)
|
||||
.unwrap();
|
||||
let listing = ws.list();
|
||||
assert!(listing.contains("label=\"gatto\""));
|
||||
assert!(listing.contains("dims=4"));
|
||||
// metadata listing carries no float values
|
||||
assert!(!listing.contains("2.0000"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_accepts_vector_scalar_either_order() {
|
||||
let mut ws = VectorWorkspace::new();
|
||||
let rep = ws
|
||||
.execute("\"ab\" EMB 0.5 SCALE NORM", &StubEmbedder)
|
||||
.unwrap();
|
||||
// [2,4,6,0]*0.5 = [1,2,3,0], norm = sqrt(14) ≈ 3.7417
|
||||
match rep.result {
|
||||
Some(Outcome::Scalar(s)) => assert!((s - 14.0f64.sqrt()).abs() < 1e-4),
|
||||
other => panic!("expected scalar norm, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Live symbolic flow against Altair: EMB two phrases into slots, COS yields a
|
||||
/// scalar (never the array); slots hold 1024-dim vectors server-side while the
|
||||
/// listing shows only metadata. `cargo test -p strata-memory -- --ignored`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn live_symbolic_cos_altair() {
|
||||
let e =
|
||||
crate::HttpEmbedder::new("http://192.168.50.18:8091", "bge-m3-q8", crate::BGE_M3_DIM);
|
||||
let mut ws = VectorWorkspace::new();
|
||||
ws.execute("\"Il gatto nero salta sul tavolo\" EMB STO $VEC[0]", &e)
|
||||
.unwrap();
|
||||
ws.execute(
|
||||
"\"Un felino scuro balza sopra il tavolo\" EMB STO $VEC[1]",
|
||||
&e,
|
||||
)
|
||||
.unwrap();
|
||||
let rep = ws.execute("RCL $VEC[0] RCL $VEC[1] COS", &e).unwrap();
|
||||
match rep.result {
|
||||
Some(Outcome::Scalar(s)) => {
|
||||
assert!(
|
||||
(0.5..=1.0).contains(&s),
|
||||
"paraphrase cosine should be high, got {s}"
|
||||
)
|
||||
}
|
||||
other => panic!("expected scalar cosine, got {other:?}"),
|
||||
}
|
||||
let listing = ws.list();
|
||||
assert!(listing.contains("dims=1024"));
|
||||
assert!(ws.render(&rep).contains("scalar"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user