Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(mcp): semantic retrieval tools (store, retrieve, update, remove) (#1250)

Kevin9c38fd49e558
diff --git a/semantica_mcp/mcp/schemas.py b/semantica_mcp/mcp/schemas.py
index 5a9f8c7c..19d7eb01 100644
--- a/semantica_mcp/mcp/schemas.py
+++ b/semantica_mcp/mcp/schemas.py
@@ -289,4 +289,122 @@ GET_ANALYTICS = {
},
}
+STORE_DOCUMENT = {
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "string",
+ "description": "Document text to chunk and store for semantic retrieval",
+ },
+ "source": {
+ "type": "string",
+ "description": "Provenance identifier, e.g. 'policy_manual_v2#page12'",
+ },
+ "authority": {
+ "type": "string",
+ "description": "Authority level of the content, e.g. 'official', 'draft', 'external'",
+ },
+ "version": {
+ "type": "string",
+ "description": "Document version tag used together with source as the upsert key (default: 'v1')",
+ },
+ "project": {
+ "type": "string",
+ "description": "Optional project namespace for later filtering",
+ },
+ "metadata": {
+ "type": "object",
+ "description": "Additional key-value properties stored on every chunk",
+ },
+ "chunk_size": {
+ "type": "integer",
+ "minimum": 100,
+ "description": "Chunk window in characters (default: 1000)",
+ },
+ "chunk_overlap": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "Overlap between consecutive chunks in characters (default: 200)",
+ },
+ },
+ "required": ["content", "source", "authority"],
+}
+
+RETRIEVE_CONTEXT = {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Natural language query to embed and search for",
+ },
+ "top_k": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 10,
+ "description": "Maximum number of chunks to return (default: 5, capped at 10)",
+ },
+ "project": {
+ "type": "string",
+ "description": "Only return chunks stored under this project namespace (optional)",
+ },
+ },
+ "required": ["query"],
+}
+
+UPDATE_DOCUMENT = {
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "string",
+ "description": "New document text replacing the stored version",
+ },
+ "source": {
+ "type": "string",
+ "description": "Provenance identifier of the document to update",
+ },
+ "version": {
+ "type": "string",
+ "description": "Version tag identifying which stored version to replace (default: 'v1')",
+ },
+ "authority": {
+ "type": "string",
+ "description": "Updated authority level (defaults to the stored value)",
+ },
+ "project": {
+ "type": "string",
+ "description": "Updated project namespace (defaults to the stored value)",
+ },
+ "metadata": {
+ "type": "object",
+ "description": "Additional key-value properties merged into chunk metadata",
+ },
+ "chunk_size": {
+ "type": "integer",
+ "minimum": 100,
+ "description": "Chunk window in characters (default: 1000)",
+ },
+ "chunk_overlap": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "Overlap between consecutive chunks in characters (default: 200)",
+ },
+ },
+ "required": ["content", "source"],
+}
+
+REMOVE_DOCUMENT = {
+ "type": "object",
+ "properties": {
+ "source": {
+ "type": "string",
+ "description": "Provenance identifier of the document to remove",
+ },
+ "version": {
+ "type": "string",
+ "description": "Version tag identifying which stored version to remove (default: 'v1')",
+ },
+ },
+ "required": ["source"],
+}
+
EMPTY = {"type": "object", "properties": {}}
diff --git a/semantica_mcp/mcp/session.py b/semantica_mcp/mcp/session.py
index da8ec7e2..9aedc325 100644
--- a/semantica_mcp/mcp/session.py
+++ b/semantica_mcp/mcp/session.py
@@ -14,7 +14,15 @@ from typing import Any, Optional
log = logging.getLogger("semantica.mcp.session")
+# Backends the retrieval tools can actually support end to end. faiss
+# and pgvector have no metadata-scoped delete, so update_document and
+# remove_document cannot work on them; selecting them fails fast here
+# instead of blowing up mid-update.
+SUPPORTED_VECTOR_BACKENDS = ("inmemory", "sqlite")
+
_graph: Optional[Any] = None
+_embedder: Optional[Any] = None
+_vector_store: Optional[Any] = None
# Tracks whether the last graph initialisation successfully loaded the
# configured SEMANTICA_KG_PATH file. When True (or no path was configured)
@@ -59,6 +67,103 @@ def get_graph() -> Any:
return _graph
+def get_embedder() -> Any:
+ """
+ Return the shared EmbeddingGenerator instance, creating it on first call.
+
+ Used by the semantic retrieval tools (#1235) to embed documents and
+ queries with one consistent model, so stored vectors and query
+ vectors always share the same dimensionality.
+ """
+ global _embedder
+ if _embedder is None:
+ from semantica.embeddings import EmbeddingGenerator
+
+ _embedder = EmbeddingGenerator()
+ log.info(
+ "Embedding generator initialised (method=%s)",
+ _embedder.get_text_method(),
+ )
+ return _embedder
+
+
+def get_vector_store() -> Any:
+ """
+ Return the shared VectorStore instance, creating it on first call.
+
+ Backend selection:
+
+ • ``SEMANTICA_VECTOR_BACKEND`` — ``inmemory`` (default) or ``sqlite``.
+ The ``sqlite`` backend additionally requires
+ ``SEMANTICA_VECTOR_DB_PATH``. Other VectorStore backends (faiss,
+ pgvector) are rejected: they lack the metadata-scoped delete the
+ update/remove tools need.
+ • ``SEMANTICA_VECTOR_PATH`` — a *directory* previously written by
+ ``VectorStore.save()``. If it exists, the store is loaded from it
+ on start. Note this is a directory, unlike SEMANTICA_KG_PATH which
+ is a single JSON file. The persisted dimension must match the
+ active embedder or startup fails — otherwise queries would either
+ error on shape mismatch or silently rank across incompatible
+ embedding spaces.
+ """
+ global _vector_store
+ if _vector_store is None:
+ from semantica.vector_store import VectorStore
+
+ backend = os.environ.get("SEMANTICA_VECTOR_BACKEND", "inmemory").strip().lower()
+ if backend not in SUPPORTED_VECTOR_BACKENDS:
+ raise ValueError(
+ f"SEMANTICA_VECTOR_BACKEND={backend!r} is not supported by the "
+ "MCP retrieval tools; supported backends: "
+ + ", ".join(SUPPORTED_VECTOR_BACKENDS)
+ )
+ config: dict = {}
+ if backend == "sqlite":
+ db_path = os.environ.get("SEMANTICA_VECTOR_DB_PATH", "").strip()
+ if not db_path:
+ raise ValueError(
+ "SEMANTICA_VECTOR_BACKEND=sqlite requires "
+ "SEMANTICA_VECTOR_DB_PATH to point at the database file"
+ )
+ config["db_path"] = db_path
+ # VectorStore defaults to dimension 768, which does not match the
+ # default embedding model (all-MiniLM-L6-v2 = 384, hash fallback
+ # = 128). Always derive it from the embedder so store and
+ # queries stay consistent.
+ embedder = get_embedder()
+ config["dimension"] = embedder.text_embedder.get_embedding_dimension()
+
+ store = VectorStore(backend=backend, config=config)
+
+ vector_path = os.environ.get("SEMANTICA_VECTOR_PATH", "").strip()
+ if vector_path and os.path.isdir(vector_path):
+ try:
+ store.load(vector_path)
+ log.info("Vector store loaded from %s", vector_path)
+ except Exception as exc:
+ raise ValueError(
+ f"Could not load vector store from {vector_path}: {exc}"
+ ) from exc
+ loaded_dim = getattr(store, "dimension", None)
+ if loaded_dim and loaded_dim != config["dimension"]:
+ raise ValueError(
+ f"Persisted vector store at {vector_path} has dimension "
+ f"{loaded_dim}, but the active embedder produces "
+ f"{config['dimension']}. Re-embed the corpus or point "
+ "SEMANTICA_VECTOR_PATH at a store built with the same model."
+ )
+
+ _vector_store = store
+ log.info("Vector store initialised (backend=%s)", backend)
+ return _vector_store
+
+
+def reset_vector_store() -> None:
+ """Reset the vector store singleton (mainly useful in tests)."""
+ global _vector_store
+ _vector_store = None
+
+
def is_persistence_safe() -> bool:
"""Return True when it is safe to write mutations back to SEMANTICA_KG_PATH.
diff --git a/semantica_mcp/mcp/tools/__init__.py b/semantica_mcp/mcp/tools/__init__.py
index 333cb133..bf5195bd 100644
--- a/semantica_mcp/mcp/tools/__init__.py
+++ b/semantica_mcp/mcp/tools/__init__.py
@@ -9,6 +9,7 @@ from .export import EXPORT_TOOLS
from .extraction import EXTRACTION_TOOLS
from .graph import GRAPH_TOOLS
from .reasoning import REASONING_TOOLS
+from .retrieval import RETRIEVAL_TOOLS
# Ordered list — exposed to the MCP client via tools/list
TOOL_DEFINITIONS = (
@@ -17,6 +18,7 @@ TOOL_DEFINITIONS = (
+ GRAPH_TOOLS
+ REASONING_TOOLS
+ EXPORT_TOOLS
+ + RETRIEVAL_TOOLS
)
__all__ = ["TOOL_DEFINITIONS"]
diff --git a/semantica_mcp/mcp/tools/retrieval.py b/semantica_mcp/mcp/tools/retrieval.py
new file mode 100644
index 00000000..52a53fec
--- /dev/null
+++ b/semantica_mcp/mcp/tools/retrieval.py
@@ -0,0 +1,533 @@
+"""
+Semantic retrieval tools — store, retrieve, update and remove documents
+in a vector store, combined with knowledge-graph context (#1235).
+
+Design notes:
+
+• Documents are chunked with a fixed sliding window (default 1000 chars,
+ 200 overlap) and every chunk carries full provenance metadata:
+ chunk_id, source, authority, version, project, content hash, status
+ and character offsets.
+• (source, version) is the upsert key. The content hash only decides
+ whether a re-store can be skipped as a no-op.
+• Updates and removals on the in-memory backend rebuild the store from
+ scratch (read everything, filter, clear, re-store) instead of calling
+ delete_vectors. In-memory ids are derived from ``len(self.vectors)``
+ and fall back after a delete, so deleting then writing can overwrite
+ live data (#1029). Rebuilding from an empty dict starts the counter
+ at zero — nothing to collide with. The real fix for #1029 (ids that
+ never get reused) belongs in its own PR.
+• Retrieval results are combined with related graph nodes: for each hit
+ source we look up ContextGraph nodes tagged with the same
+ ``metadata.source`` and attach their 1-hop neighbours.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import os
+from typing import Any, Dict, List, Tuple
+
+import numpy as np
+
+from ..schemas import (
+ REMOVE_DOCUMENT,
+ RETRIEVE_CONTEXT,
+ STORE_DOCUMENT,
+ UPDATE_DOCUMENT,
+)
+from ..session import get_embedder, get_graph, get_vector_store
+
+log = logging.getLogger("semantica.mcp.tools.retrieval")
+
+DEFAULT_CHUNK_SIZE = 1000
+DEFAULT_CHUNK_OVERLAP = 200
+MAX_TOP_K = 10
+FILTER_OVERFETCH = 3
+MAX_FILTER_MATCHES = 10_000
+MAX_CHUNKS_PER_DOC = 10_000
+
+# Metadata fields owned by the upsert logic. Caller-supplied metadata
+# can add extra context but must not rewrite provenance: overwriting
+# source/version/hash/status would break the (source, version) upsert
+# key, the idempotent no-op check, and retrieval filters.
+PROTECTED_META_KEYS = frozenset(
+ {
+ "chunk_id",
+ "text",
+ "source",
+ "authority",
+ "version",
+ "hash",
+ "status",
+ "chunk_index",
+ "char_start",
+ "char_end",
+ "project",
+ }
+)
+
+
+def _chunk_text(text: str, chunk_size: int, chunk_overlap: int) -> List[Tuple[int, int, str]]:
+ """Split text into (char_start, char_end, chunk) windows."""
+ if chunk_overlap >= chunk_size:
+ raise ValueError("chunk_overlap must be smaller than chunk_size")
+ chunks: List[Tuple[int, int, str]] = []
+ start = 0
+ n = len(text)
+ while start < n:
+ end = min(start + chunk_size, n)
+ chunks.append((start, end, text[start:end]))
+ if end >= n:
+ break
+ start = end - chunk_overlap
+ return chunks
+
+
+def _chunk_id(source: str, version: str, index: int, text: str) -> str:
+ """Stable chunk id derived from the location key and chunk content."""
+ digest = hashlib.sha256(
+ f"{source}|{version}|{index}|{text}".encode("utf-8")
+ ).hexdigest()
+ return f"chk_{digest[:16]}"
+
+
+def _doc_hash(content: str) -> str:
+ return hashlib.sha256(content.encode("utf-8")).hexdigest()
+
+
+def _find_matching_rows(store: Any, source: str, version: str) -> List[Dict[str, Any]]:
+ """
+ Return rows (``{id, vector, metadata}``) matching (source, version).
+
+ The persistent branch pulls whole rows (vector included) into memory;
+ the limit keeps the scan bounded. Documents beyond MAX_CHUNKS_PER_DOC
+ chunks are rejected at ingestion, so the cap cannot leave stale
+ chunks behind on update/remove.
+ """
+ if getattr(store, "backend", "") == "inmemory":
+ rows = []
+ for vid, vec in getattr(store, "vectors", {}).items():
+ meta = getattr(store, "metadata", {}).get(vid) or {}
+ if meta.get("source") == source and meta.get("version") == version:
+ rows.append({"id": vid, "vector": vec, "metadata": meta})
+ return rows
+ backend_store = getattr(store, "_backend_store", None)
+ if backend_store is not None and hasattr(backend_store, "filter_by_metadata"):
+ return backend_store.filter_by_metadata(
+ {"source": source, "version": version}, limit=MAX_FILTER_MATCHES
+ )
+ raise NotImplementedError(
+ f"Backend {type(backend_store).__name__} does not support metadata lookup; "
+ "cannot locate chunks for update/remove"
+ )
+
+
+def _find_matching_ids(store: Any, source: str, version: str) -> List[str]:
+ """Return every vector id whose metadata matches (source, version)."""
+ return [row["id"] for row in _find_matching_rows(store, source, version)]
+
+
+def _remove_ids(store: Any, remove_ids: List[str]) -> None:
+ """Remove vectors by id, avoiding the #1029 in-memory id collision."""
+ if getattr(store, "backend", "") == "inmemory":
+ # Full rebuild: read all, filter in memory, clear, re-store once.
+ # store_vectors derives ids from len(self.vectors), and the dicts
+ # are empty here, so the counter restarts at zero — no reuse of
+ # ids that are still referenced anywhere.
+ remove = set(remove_ids)
+ vectors = getattr(store, "vectors", {})
+ metadata = getattr(store, "metadata", {})
+ saved_vectors = dict(vectors)
+ saved_metadata = dict(metadata)
+ keep_vectors = []
+ keep_meta = []
+ for vid, vec in list(vectors.items()):
+ if vid in remove:
+ continue
+ keep_vectors.append(vec)
+ keep_meta.append(metadata.get(vid, {}))
+ vectors.clear()
+ metadata.clear()
+ try:
+ if keep_vectors:
+ store.store_vectors(keep_vectors, keep_meta)
+ except Exception:
+ # Restore the pre-rebuild state so a failed re-store does not
+ # silently drop every surviving document.
+ vectors.update(saved_vectors)
+ metadata.update(saved_metadata)
+ store.indexer.create_index(
+ list(vectors.values()), list(vectors.keys())
+ )
+ raise
+ return
+ # Persistent backends do not have the len-based id collision, so a
+ # direct delete is safe there.
+ store.delete_vectors(remove_ids)
+
+
+def _persist(store: Any) -> Any:
+ """
+ Persist the store when SEMANTICA_VECTOR_PATH is configured.
+
+ Returns ``None`` when no path is configured, ``True`` on success and
+ ``False`` when saving failed — surfaced in tool results so a caller
+ can tell an in-memory-only write from a durable one.
+ """
+ path = os.environ.get("SEMANTICA_VECTOR_PATH", "").strip()
+ if not path:
+ return None
+ try:
+ store.save(path)
+ except Exception as exc:
+ log.warning("Could not persist vector store to %s: %s", path, exc)
+ return False
+ return True
+
+
+def _node_source(meta: Any) -> str:
+ """
+ Extract a node's source tag from its metadata.
+
+ ContextGraph.add_node nests the caller-supplied metadata dict one
+ level down (``{'label': ..., 'metadata': {...}}``), while nodes added
+ through other paths may carry ``source`` directly. Check both.
+ """
+ if not isinstance(meta, dict):
+ return ""
+ direct = meta.get("source")
+ if direct:
+ return str(direct)
+ nested = meta.get("metadata")
+ if isinstance(nested, dict):
+ return str(nested.get("source", "") or "")
+ return ""
+
+
+def _graph_relationships(sources: List[str], max_per_source: int = 3) -> List[Dict[str, Any]]:
+ """
+ Collect 1-hop graph neighbours for nodes tagged with the hit sources.
+
+ Node lookup matches the node's source tag against the stored document
+ sources. Failures degrade to an empty list — graph context is a
+ bonus, never a hard dependency of retrieval.
+ """
+ if not sources:
+ return []
+ try:
+ graph = get_graph()
+ nodes = list(graph.find_nodes())
+ except Exception as exc:
+ log.debug("Graph context unavailable: %s", exc)
+ return []
+
+ relationships: List[Dict[str, Any]] = []
+ seen: set = set()
+ for source in sources:
+ anchor = None
+ for n in nodes:
+ if _node_source(n.get("metadata")) == source:
+ anchor = n
+ break
+ if anchor is None:
+ continue
+ try:
+ neighbors = graph.get_neighbors(anchor["id"], hops=1)
+ except Exception as exc:
+ log.debug("get_neighbors failed for %s: %s", anchor.get("id"), exc)
+ continue
+ added = 0
+ for nb in neighbors:
+ key = (anchor.get("id"), nb.get("id"), nb.get("relationship"))
+ if key in seen:
+ continue
+ seen.add(key)
+ relationships.append(
+ {
+ "node": {
+ "id": anchor.get("id"),
+ "type": anchor.get("type"),
+ "content": str(anchor.get("content") or "")[:200],
+ "source": source,
+ },
+ "related": {
+ "id": nb.get("id"),
+ "type": nb.get("type"),
+ "content": str(nb.get("content") or "")[:200],
+ },
+ "relationship": nb.get("relationship"),
+ }
+ )
+ added += 1
+ if added >= max_per_source:
+ break
+ return relationships
+
+
+def _upsert(args: dict, action: str) -> dict:
+ """Shared implementation for store_document and update_document."""
+ content = args.get("content", "")
+ source = str(args.get("source", "")).strip()
+ if not content or not source:
+ return {"error": "content and source are required"}
+ authority = str(args.get("authority", "")).strip()
+ if action == "store" and not authority:
+ return {"error": "authority is required"}
+ version = str(args.get("version", "")).strip() or "v1"
+ project = str(args.get("project", "")).strip() or None
+ chunk_size = int(args.get("chunk_size", DEFAULT_CHUNK_SIZE))
+ chunk_overlap = int(args.get("chunk_overlap", DEFAULT_CHUNK_OVERLAP))
+ if chunk_overlap >= chunk_size:
+ return {"error": "chunk_overlap must be smaller than chunk_size"}
+ extra = args.get("metadata") or {}
+ if not isinstance(extra, dict):
+ return {"error": "metadata must be an object"}
+ doc_hash = _doc_hash(content)
+
+ try:
+ store = get_vector_store()
+ embedder = get_embedder()
+
+ existing_ids = _find_matching_ids(store, source, version)
+ if action == "update" and not existing_ids:
+ return {"status": "not_found", "source": source, "version": version}
+ existing_first: Dict[str, Any] = {}
+ if existing_ids:
+ existing_first = store.get_metadata(existing_ids[0]) or {}
+ if action == "store" and existing_first.get("hash") == doc_hash:
+ # Same content already stored under (source, version) —
+ # skip re-embedding entirely.
+ return {
+ "status": "unchanged",
+ "source": source,
+ "version": version,
+ "chunk_ids": [
+ (store.get_metadata(vid) or {}).get("chunk_id")
+ for vid in existing_ids
+ ],
+ }
+
+ chunks = _chunk_text(content, chunk_size, chunk_overlap)
+ if len(chunks) > MAX_CHUNKS_PER_DOC:
+ return {
+ "error": (
+ f"document produces {len(chunks)} chunks, above the "
+ f"{MAX_CHUNKS_PER_DOC}-chunk limit; split it into smaller "
+ "documents or raise chunk_size"
+ )
+ }
+ vectors = np.asarray(
+ embedder.generate_embeddings([c_text for _, _, c_text in chunks])
+ )
+ if vectors.ndim == 1:
+ vectors = vectors.reshape(1, -1)
+ if vectors.shape[0] != len(chunks):
+ return {
+ "error": (
+ f"embedder returned {vectors.shape[0]} vectors "
+ f"for {len(chunks)} chunks"
+ )
+ }
+
+ final_authority = authority or existing_first.get("authority") or "unknown"
+ final_project = project or existing_first.get("project")
+
+ old_rows: List[Dict[str, Any]] = []
+ if existing_ids:
+ # Snapshot the rows being replaced so a failed write of the
+ # new chunks can put the old document back instead of leaving
+ # (source, version) silently empty.
+ old_rows = _find_matching_rows(store, source, version)
+ _remove_ids(store, existing_ids)
+
+ metas = []
+ chunk_ids = []
+ for idx, (start, end, c_text) in enumerate(chunks):
+ cid = _chunk_id(source, version, idx, c_text)
+ chunk_ids.append(cid)
+ meta: Dict[str, Any] = {
+ "chunk_id": cid,
+ "text": c_text,
+ "source": source,
+ "authority": final_authority,
+ "version": version,
+ "hash": doc_hash,
+ "status": "active",
+ "chunk_index": idx,
+ "char_start": start,
+ "char_end": end,
+ }
+ if final_project:
+ meta["project"] = final_project
+ for key in extra:
+ if key in PROTECTED_META_KEYS:
+ log.debug(
+ "Ignoring caller metadata key %r: provenance field is "
+ "managed by the tool",
+ key,
+ )
+ else:
+ meta[key] = extra[key]
+ metas.append(meta)
+
+ try:
+ store.store_vectors(list(vectors), metas)
+ except Exception:
+ if old_rows:
+ log.warning(
+ "Storing new chunks failed for (%s, %s); restoring the "
+ "previous document",
+ source,
+ version,
+ )
+ store.store_vectors(
+ [row["vector"] for row in old_rows],
+ [row["metadata"] for row in old_rows],
+ )
+ raise
+ persisted = _persist(store)
+ return {
+ "status": "stored" if action == "store" else "updated",
+ "source": source,
+ "version": version,
+ "chunk_ids": chunk_ids,
+ "chunk_count": len(chunk_ids),
+ "hash": doc_hash,
+ "persisted": persisted,
+ }
+ except Exception as exc:
+ log.exception("%s_document failed", action)
+ return {"error": str(exc)}
+
+
+def handle_store_document(args: dict) -> dict:
+ """Chunk a document, embed it, and store it for semantic retrieval."""
+ return _upsert(args, "store")
+
+
+def handle_update_document(args: dict) -> dict:
+ """Replace the stored content of a (source, version) document."""
+ return _upsert(args, "update")
+
+
+def handle_retrieve_context(args: dict) -> dict:
+ """Embed a query and return the most relevant stored chunks."""
+ query = str(args.get("query", "")).strip()
+ if not query:
+ return {"error": "query is required", "results": []}
+ try:
+ top_k = max(1, min(int(args.get("top_k", 5)), MAX_TOP_K))
+ except (TypeError, ValueError):
+ top_k = 5
+ project = str(args.get("project", "")).strip() or None
+
+ try:
+ store = get_vector_store()
+ query_vector = np.asarray(get_embedder().generate_embeddings([query]))[0]
+ # Over-fetch so a project filter can drop hits without starving
+ # the result list.
+ fetch_k = top_k * FILTER_OVERFETCH if project else top_k
+ raw = store.search_vectors(query_vector, k=fetch_k)
+
+ results = []
+ for hit in raw:
+ meta = hit.get("metadata") or {}
+ if project and meta.get("project") != project:
+ continue
+ results.append(
+ {
+ "chunk_id": meta.get("chunk_id", hit.get("id")),
+ "text": meta.get("text", ""),
+ "score": hit.get("score"),
+ "source": meta.get("source"),
+ "authority": meta.get("authority"),
+ "version": meta.get("version"),
+ "project": meta.get("project"),
+ "status": meta.get("status"),
+ "hash": meta.get("hash"),
+ }
+ )
+ if len(results) >= top_k:
+ break
+
+ sources = list(dict.fromkeys(r["source"] for r in results if r["source"]))
+ return {
+ "query": query,
+ "results": results,
+ "count": len(results),
+ "graph_context": _graph_relationships(sources),
+ }
+ except Exception as exc:
+ log.exception("retrieve_context failed")
+ return {"error": str(exc), "results": []}
+
+
+def handle_remove_document(args: dict) -> dict:
+ """Remove every chunk stored under (source, version)."""
+ source = str(args.get("source", "")).strip()
+ if not source:
+ return {"error": "source is required"}
+ version = str(args.get("version", "")).strip() or "v1"
+ try:
+ store = get_vector_store()
+ existing_ids = _find_matching_ids(store, source, version)
+ if not existing_ids:
+ return {"status": "not_found", "source": source, "version": version}
+ _remove_ids(store, existing_ids)
+ persisted = _persist(store)
+ return {
+ "status": "removed",
+ "source": source,
+ "version": version,
+ "removed_chunks": len(existing_ids),
+ "persisted": persisted,
+ }
+ except Exception as exc:
+ log.exception("remove_document failed")
+ return {"error": str(exc)}
+
+
+RETRIEVAL_TOOLS = [
+ {
+ "name": "store_document",
+ "description": (
+ "Chunk a document, embed the chunks, and store them for semantic "
+ "retrieval. Keyed on (source, version); storing identical content "
+ "again is a no-op."
+ ),
+ "inputSchema": STORE_DOCUMENT,
+ "_handler": handle_store_document,
+ },
+ {
+ "name": "retrieve_context",
+ "description": (
+ "Embed a natural-language query and return the most relevant "
+ "stored chunks with scores and provenance, combined with related "
+ "knowledge-graph relationships."
+ ),
+ "inputSchema": RETRIEVE_CONTEXT,
+ "_handler": handle_retrieve_context,
+ },
+ {
+ "name": "update_document",
+ "description": (
+ "Replace the stored content of a document identified by "
+ "(source, version). Old chunks are removed and the new content "
+ "is re-chunked and re-embedded. Returns not_found when no "
+ "stored document matches (source, version)."
+ ),
+ "inputSchema": UPDATE_DOCUMENT,
+ "_handler": handle_update_document,
+ },
+ {
+ "name": "remove_document",
+ "description": (
+ "Remove every chunk stored under (source, version) from the "
+ "vector store."
+ ),
+ "inputSchema": REMOVE_DOCUMENT,
+ "_handler": handle_remove_document,
+ },
+]
diff --git a/tests/test_mcp_semantic_retrieval.py b/tests/test_mcp_semantic_retrieval.py
new file mode 100644
index 00000000..c847ea2c
--- /dev/null
+++ b/tests/test_mcp_semantic_retrieval.py
@@ -0,0 +1,787 @@
+"""
+Tests for the MCP semantic retrieval tools (#1235).
+
+Covers the six acceptance behaviours proposed in the issue:
+
+1. store_document chunks content and stores it in a real supported
+ vector backend with provenance metadata (status / version / hash).
+2. retrieve_context returns semantically relevant chunks with scores
+ and provenance, combined with related graph relationships.
+3. update_document replaces stored content under (source, version).
+4. remove_document deletes every chunk of a document.
+5. Remove-then-store does not collide with surviving in-memory ids
+ (regression guard for the #1029 interaction).
+6. The same tool set works against the sqlite backend (real persistent
+ store, skipped when the sqlite_vec extension is missing).
+"""
+
+import os
+import sys
+import tempfile
+import unittest
+import zlib
+from unittest.mock import patch
+
+import numpy as np
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
+
+import semantica_mcp.mcp.session as session
+import semantica.embeddings as _embeddings_pkg
+import semantica.vector_store.vector_store as _vs_module
+from semantica_mcp.mcp.session import get_vector_store, reset_vector_store
+from semantica_mcp.mcp.tools import TOOL_DEFINITIONS
+from semantica_mcp.mcp.tools.retrieval import (
+ _chunk_id,
+ _chunk_text,
+ handle_remove_document,
+ handle_retrieve_context,
+ handle_store_document,
+ handle_update_document,
+)
+
+
+class FakeTextEmbedder:
+ def __init__(self, dim: int = 64):
+ self.dim = dim
+
+ def get_embedding_dimension(self) -> int:
+ return self.dim
+
+
+class FakeEmbedder:
+ """
+ Deterministic keyword-bag embedder on a fixed dimension.
+
+ Same words land on the same dimensions, so a query sharing vocabulary
+ with a chunk scores higher than one that does not — enough signal for
+ ranking assertions without any model download. crc32 keeps the
+ word-to-dimension mapping stable across processes (unlike builtin
+ hash(), whose per-process salt would make collisions flaky), and 64
+ dims keep the test keywords collision-free.
+ """
+
+ def __init__(self, dim: int = 64):
+ self.dim = dim
+ self.text_embedder = FakeTextEmbedder(dim)
+
+ def get_text_method(self) -> str:
+ return "fake"
+
+ def generate_embeddings(self, texts):
+ out = []
+ for t in texts:
+ v = np.zeros(self.dim, dtype=float)
+ for w in str(t).lower().split():
+ if w == "x":
+ # "x" is the filler make_doc pads with; treating it
+ # as a stopword keeps vectors keyword-driven instead
+ # of filler-dominated.
+ continue
+ v[zlib.crc32(w.encode("utf-8")) % self.dim] += 1.0
+ norm = np.linalg.norm(v)
+ if norm:
+ v /= norm
+ out.append(v)
+ return np.array(out)
+
+
+def make_doc(*keywords) -> str:
+ """
+ Build filler text with exactly one keyword per chunk.
+
+ With the default 1000 window / 200 overlap, chunk i covers
+ [800*i, 800*i+1000). Keyword i is placed at 800*i + 300, which sits
+ inside chunk i only — clear of both neighbouring overlap zones.
+ Filler is spaced "x " tokens, which the fake embedder treats as a
+ stopword, so chunk vectors are keyword-driven.
+ """
+ filler = "x "
+ parts = []
+ pos = 0
+ for i, word in enumerate(keywords):
+ target = 800 * i + 300
+ parts.append(filler * ((target - pos) // 2))
+ parts.append(word + " ")
+ pos = target + len(word) + 1
+ parts.append(filler * 30)
+ return "".join(parts)
+
+
+def patch_embedding_generators():
+ """
+ Patch every EmbeddingGenerator construction site with FakeEmbedder.
+
+ The real EmbeddingGenerator probes FastEmbed / sentence-transformers
+ on init; where those packages are installed but the model is not
+ cached, the probe blocks on a full TCP connect timeout (~30s each).
+ VectorStore's in-memory branch builds one internally, so tests patch
+ both import sites to keep the suite fast and network-free.
+ """
+ return (
+ patch.object(_embeddings_pkg, "EmbeddingGenerator", FakeEmbedder),
+ patch.object(_vs_module, "EmbeddingGenerator", FakeEmbedder),
+ )
+
+
+def _clear_retrieval_env():
+ for var in ("SEMANTICA_VECTOR_PATH", "SEMANTICA_VECTOR_BACKEND", "SEMANTICA_VECTOR_DB_PATH"):
+ os.environ.pop(var, None)
+
+
+class InmemoryBackendTestBase(unittest.TestCase):
+ def setUp(self):
+ _clear_retrieval_env()
+ session._embedder = FakeEmbedder()
+ session._vector_store = None
+ session._graph = None
+ self._patches = patch_embedding_generators()
+ for p in self._patches:
+ p.start()
+
+ def tearDown(self):
+ for p in self._patches:
+ p.stop()
+ session._embedder = None
+ reset_vector_store()
+ session._graph = None
+ _clear_retrieval_env()
+
+
+class TestChunking(InmemoryBackendTestBase):
+ def test_fixed_window_with_overlap(self):
+ text = "a" * 2600
+ chunks = _chunk_text(text, 1000, 200)
+ self.assertEqual([c[:2] for c in chunks], [(0, 1000), (800, 1800), (1600, 2600)])
+ self.assertTrue(all(c == text[s:e] for s, e, c in chunks))
+
+ def test_short_text_single_chunk(self):
+ chunks = _chunk_text("short", 1000, 200)
+ self.assertEqual(chunks, [(0, 5, "short")])
+
+ def test_overlap_must_be_smaller_than_window(self):
+ with self.assertRaises(ValueError):
+ _chunk_text("abc", 200, 200)
+
+ def test_chunk_id_is_stable_and_position_sensitive(self):
+ a = _chunk_id("src", "v1", 0, "hello")
+ b = _chunk_id("src", "v1", 0, "hello")
+ c = _chunk_id("src", "v1", 1, "hello")
+ self.assertEqual(a, b)
+ self.assertNotEqual(a, c)
+
+
+class TestStoreDocument(InmemoryBackendTestBase):
+ def test_chunks_carry_provenance_metadata(self):
+ result = handle_store_document(
+ {
+ "content": make_doc("alpha", "beta"),
+ "source": "policy_manual#p12",
+ "authority": "official",
+ "version": "v2",
+ "project": "lending",
+ }
+ )
+ self.assertNotIn("error", result)
+ self.assertEqual(result["status"], "stored")
+ self.assertEqual(result["chunk_count"], len(result["chunk_ids"]))
+
+ store = get_vector_store()
+ first = next(
+ m
+ for m in store.metadata.values()
+ if m.get("source") == "policy_manual#p12" and m.get("chunk_index") == 0
+ )
+ self.assertEqual(first["chunk_id"], result["chunk_ids"][0])
+ self.assertEqual(first["authority"], "official")
+ self.assertEqual(first["version"], "v2")
+ self.assertEqual(first["project"], "lending")
+ self.assertEqual(first["status"], "active")
+ self.assertEqual(first["hash"], result["hash"])
+ self.assertEqual(first["char_start"], 0)
+
+ def test_identical_content_is_a_noop(self):
+ args = {"content": "same content", "source": "doc", "authority": "official"}
+ first = handle_store_document(args)
+ second = handle_store_document(args)
+ self.assertEqual(second["status"], "unchanged")
+ self.assertEqual(second["chunk_ids"], first["chunk_ids"])
+ self.assertEqual(get_vector_store().count(), first["chunk_count"])
+
+ def test_missing_authority_rejected(self):
+ result = handle_store_document({"content": "text", "source": "doc"})
+ self.assertIn("error", result)
+
+ def test_caller_metadata_cannot_override_provenance(self):
+ result = handle_store_document(
+ {
+ "content": make_doc("alpha"),
+ "source": "real_source",
+ "authority": "official",
+ "metadata": {
+ "source": "spoofed_source",
+ "authority": "backdated",
+ "status": "tombstone",
+ "hash": "deadbeef",
+ "version": "v99",
+ "project": "shadow_project",
+ "dept": "risk",
+ },
+ }
+ )
+ self.assertNotIn("error", result)
+
+ store = get_vector_store()
+ meta = next(
+ m
+ for m in store.metadata.values()
+ if m.get("chunk_id") == result["chunk_ids"][0]
+ )
+ self.assertEqual(meta["source"], "real_source")
+ self.assertEqual(meta["authority"], "official")
+ self.assertEqual(meta["status"], "active")
+ self.assertEqual(meta["hash"], result["hash"])
+ self.assertEqual(meta["version"], "v1")
+ self.assertNotIn("project", meta)
+ # Non-provenance keys still land.
+ self.assertEqual(meta["dept"], "risk")
+
+ # Provenance stays intact, so the idempotent no-op still works.
+ again = handle_store_document(
+ {
+ "content": make_doc("alpha"),
+ "source": "real_source",
+ "authority": "official",
+ }
+ )
+ self.assertEqual(again["status"], "unchanged")
+
+ def test_non_dict_metadata_rejected(self):
+ result = handle_store_document(
+ {"content": "text", "source": "doc", "authority": "official", "metadata": ["bad"]}
+ )
+ self.assertIn("error", result)
+
+
+class TestRetrieveContext(InmemoryBackendTestBase):
+ def setUp(self):
+ super().setUp()
+ handle_store_document(
+ {
+ "content": make_doc("approval", "collateral", "interest"),
+ "source": "lending_policy",
+ "authority": "official",
+ "project": "lending",
+ }
+ )
+ handle_store_document(
+ {
+ "content": make_doc("payment", "refund"),
+ "source": "billing_faq",
+ "authority": "draft",
+ "project": "billing",
+ }
+ )
+
+ def test_relevant_chunks_ranked_with_provenance(self):
+ result = handle_retrieve_context({"query": "collateral", "top_k": 3})
+ self.assertNotIn("error", result)
+ self.assertGreater(result["count"], 0)
+ relevant = [r for r in result["results"] if r["score"] and r["score"] > 0]
+ self.assertTrue(relevant)
+ top = relevant[0]
+ self.assertIn("collateral", top["text"])
+ self.assertEqual(top["source"], "lending_policy")
+ self.assertEqual(top["authority"], "official")
+ self.assertEqual(top["version"], "v1")
+ self.assertEqual(top["status"], "active")
+ self.assertTrue(top["hash"])
+ self.assertIsInstance(top["score"], float)
+
+ def test_top_k_is_capped_at_ten(self):
+ # 13 chunks (one keyword per chunk) so the cap is actually hit;
+ # with fewer stored chunks the assertion would pass trivially.
+ handle_store_document(
+ {
+ "content": make_doc(*["k%02d" % i for i in range(1, 14)]),
+ "source": "capdoc",
+ "authority": "official",
+ }
+ )
+ result = handle_retrieve_context({"query": "k01", "top_k": 99})
+ self.assertEqual(result["count"], 10)
+
+ def test_project_filter_narrows_results(self):
+ result = handle_retrieve_context({"query": "collateral", "project": "billing"})
+ for r in result["results"]:
+ self.assertEqual(r["project"], "billing")
+
+ def test_graph_relationships_attached(self):
+ graph = session.get_graph()
+ graph.add_node(
+ node_id="policy_doc_lending_policy",
+ label="Lending policy doc",
+ node_type="Document",
+ metadata={"source": "lending_policy"},
+ )
+ graph.add_node(node_id="risk_team", label="Risk team", node_type="Team")
+ graph.add_edge(
+ source_id="policy_doc_lending_policy",
+ target_id="risk_team",
+ edge_type="OWNED_BY",
+ )
+ result = handle_retrieve_context({"query": "collateral"})
+ self.assertGreaterEqual(len(result["graph_context"]), 1)
+ rel = result["graph_context"][0]
+ self.assertEqual(rel["node"]["source"], "lending_policy")
+ self.assertEqual(rel["related"]["id"], "risk_team")
+ self.assertEqual(rel["relationship"], "OWNED_BY")
+
+ def test_empty_query_rejected(self):
+ result = handle_retrieve_context({"query": " "})
+ self.assertIn("error", result)
+
+
+class TestUpdateDocument(InmemoryBackendTestBase):
+ def test_update_replaces_chunks(self):
+ handle_store_document(
+ {
+ "content": make_doc("oldterm", "legacy"),
+ "source": "handbook",
+ "authority": "official",
+ }
+ )
+ result = handle_update_document(
+ {
+ "content": make_doc("newterm"),
+ "source": "handbook",
+ "version": "v1",
+ }
+ )
+ self.assertEqual(result["status"], "updated")
+ self.assertEqual(result["chunk_count"], 1)
+
+ hits = handle_retrieve_context({"query": "newterm"})["results"]
+ hits = [h for h in hits if h["score"] and h["score"] > 0]
+ self.assertTrue(hits and "newterm" in hits[0]["text"])
+ stale = handle_retrieve_context({"query": "oldterm"})["results"]
+ stale = [h for h in stale if h["score"] and h["score"] > 0]
+ self.assertEqual(stale, [])
+ # Authority is inherited from the stored version when omitted.
+ self.assertEqual(hits[0]["authority"], "official")
+ self.assertEqual(get_vector_store().count(), 1)
+
+ def test_update_rolls_back_when_new_write_fails(self):
+ handle_store_document(
+ {
+ "content": make_doc("oldterm", "legacy"),
+ "source": "handbook",
+ "authority": "official",
+ }
+ )
+ store = get_vector_store()
+ real_store_vectors = store.store_vectors
+
+ def failing_write(vectors, metas):
+ if any("phoenix" in (m.get("text") or "") for m in metas):
+ raise RuntimeError("simulated write failure")
+ return real_store_vectors(vectors, metas)
+
+ with patch.object(store, "store_vectors", side_effect=failing_write):
+ result = handle_update_document(
+ {"content": make_doc("phoenix"), "source": "handbook"}
+ )
+ self.assertIn("error", result)
+ self.assertIn("simulated write failure", result["error"])
+
+ # The old document must survive the failed replacement, with no
+ # trace of the new content.
+ store = get_vector_store()
+ self.assertEqual(store.count(), 2)
+ old = [
+ h
+ for h in handle_retrieve_context({"query": "oldterm"})["results"]
+ if h["score"] and h["score"] > 0
+ ]
+ self.assertTrue(old and "oldterm" in old[0]["text"])
+ self.assertEqual(old[0]["source"], "handbook")
+ self.assertEqual(old[0]["authority"], "official")
+ phoenix = [
+ h
+ for h in handle_retrieve_context({"query": "phoenix"})["results"]
+ if h["score"] and h["score"] > 0
+ ]
+ self.assertEqual(phoenix, [])
+
+ def test_update_missing_document_reports_not_found(self):
+ result = handle_update_document(
+ {
+ "content": make_doc("neverseen"),
+ "source": "never_stored",
+ "version": "v1",
+ }
+ )
+ self.assertEqual(result["status"], "not_found")
+ self.assertEqual(result["source"], "never_stored")
+ self.assertEqual(result["version"], "v1")
+ self.assertEqual(get_vector_store().count(), 0)
+
+
+class TestRemoveDocument(InmemoryBackendTestBase):
+ def test_remove_deletes_every_chunk(self):
+ handle_store_document(
+ {
+ "content": make_doc("alpha", "beta", "gamma"),
+ "source": "docA",
+ "authority": "official",
+ }
+ )
+ result = handle_remove_document({"source": "docA"})
+ self.assertEqual(result["status"], "removed")
+ self.assertEqual(result["removed_chunks"], 3)
+ self.assertEqual(get_vector_store().count(), 0)
+ again = handle_remove_document({"source": "docA"})
+ self.assertEqual(again["status"], "not_found")
+
+ def test_remove_missing_document_reports_not_found(self):
+ result = handle_remove_document({"source": "never_stored"})
+ self.assertEqual(result["status"], "not_found")
+
+
+class TestInMemoryIdCollisionRegression(InmemoryBackendTestBase):
+ """
+ #1029 interaction guard.
+
+ In-memory vector ids are ``vec_{len(self.vectors) + i}``. Deleting a
+ document that is NOT a suffix makes len() fall below surviving ids, so
+ the next plain write overwrites live data. Our rebuild path must
+ prevent that: store a 1-chunk doc, then a 3-chunk doc, remove the
+ 1-chunk one, then store another doc. Without the rebuild the last
+ store lands on the surviving document's third chunk id and destroys
+ it.
+ """
+
+ def test_remove_then_store_keeps_surviving_chunks_intact(self):
+ handle_store_document(
+ {"content": make_doc("alpha"), "source": "docA", "authority": "official"}
+ )
+ handle_store_document(
+ {
+ "content": make_doc("bravo", "charlie", "delta"),
+ "source": "docB",
+ "authority": "official",
+ }
+ )
+ self.assertEqual(get_vector_store().count(), 4)
+
+ removed = handle_remove_document({"source": "docA"})
+ self.assertEqual(removed["status"], "removed")
+
+ stored = handle_store_document(
+ {"content": make_doc("echo"), "source": "docC", "authority": "official"}
+ )
+ self.assertEqual(stored["status"], "stored")
+
+ store = get_vector_store()
+ self.assertEqual(store.count(), 4)
+
+ delta_hits = handle_retrieve_context({"query": "delta"})["results"]
+ delta_hits = [h for h in delta_hits if h["score"] and h["score"] > 0]
+ self.assertTrue(delta_hits, "docB's third chunk was destroyed by an id collision")
+ self.assertIn("delta", delta_hits[0]["text"])
+ self.assertEqual(delta_hits[0]["source"], "docB")
+
+ for keyword, expected_source in (
+ ("bravo", "docB"),
+ ("charlie", "docB"),
+ ("echo", "docC"),
+ ):
+ hits = [
+ h
+ for h in handle_retrieve_context({"query": keyword})["results"]
+ if h["score"] and h["score"] > 0
+ ]
+ self.assertTrue(hits, f"expected a hit for {keyword}")
+ self.assertEqual(hits[0]["source"], expected_source)
+
+
+class TestBackendPolicy(InmemoryBackendTestBase):
+ def test_unsupported_backend_fails_fast(self):
+ # faiss/pgvector lack a metadata-scoped delete, so update/remove
+ # cannot work on them; selecting them must fail at startup, not
+ # mid-update.
+ for backend in ("faiss", "pgvector"):
+ with self.subTest(backend=backend):
+ os.environ["SEMANTICA_VECTOR_BACKEND"] = backend
+ with self.assertRaises(ValueError) as ctx:
+ get_vector_store()
+ self.assertIn("not supported", str(ctx.exception))
+
+ def test_oversized_document_rejected_before_embedding(self):
+ # chunk_size=1 turns a 12k-char body into 12k chunks, crossing
+ # the ingestion cap without any expensive embedding work.
+ result = handle_store_document(
+ {
+ "content": "ab" * 6000,
+ "source": "bigdoc",
+ "authority": "official",
+ "chunk_size": 1,
+ "chunk_overlap": 0,
+ }
+ )
+ self.assertIn("error", result)
+ self.assertIn("chunks", result["error"])
+ self.assertEqual(get_vector_store().count(), 0)
+
+
+class TestToolRegistration(unittest.TestCase):
+ def test_retrieval_tools_are_registered(self):
+ retrieval = {
+ t["name"]: t
+ for t in TOOL_DEFINITIONS
+ if t["name"] in ("store_document", "retrieve_context", "update_document", "remove_document")
+ }
+ self.assertEqual(len(retrieval), 4)
+ for name, t in retrieval.items():
+ self.assertTrue(callable(t["_handler"]))
+ self.assertIn("required", t["inputSchema"])
+
+
+class TestSqliteBackend(unittest.TestCase):
+ def setUp(self):
+ try:
+ import sqlite_vec # noqa: F401
+ except ImportError:
+ self.skipTest("sqlite_vec extension not installed")
+ self.tmpdir = tempfile.mkdtemp(prefix="semantica_sqlite_test_")
+ self.patches = patch_embedding_generators()
+ for p in self.patches:
+ p.start()
+ _clear_retrieval_env()
+ os.environ["SEMANTICA_VECTOR_BACKEND"] = "sqlite"
+ os.environ["SEMANTICA_VECTOR_DB_PATH"] = os.path.join(self.tmpdir, "vectors.db")
+ session._embedder = FakeEmbedder()
+ session._vector_store = None
+
+ def tearDown(self):
+ for p in self.patches:
+ p.stop()
+ session._embedder = None
+ reset_vector_store()
+ _clear_retrieval_env()
+ import shutil
+
+ shutil.rmtree(self.tmpdir, ignore_errors=True)
+
+ def test_sqlite_backend_roundtrip(self):
+ handle_store_document(
+ {
+ "content": make_doc("alpha", "beta"),
+ "source": "docS",
+ "authority": "official",
+ }
+ )
+ hits = handle_retrieve_context({"query": "beta"})["results"]
+ self.assertTrue(hits and "beta" in hits[0]["text"])
+ self.assertEqual(hits[0]["source"], "docS")
+
+ updated = handle_update_document(
+ {"content": make_doc("gamma"), "source": "docS"}
+ )
+ self.assertEqual(updated["status"], "updated")
+ # NB: score scales differ across backends (sqlite maps distance
+ # through 1/(1+d), so an orthogonal chunk still scores 0.5).
+ # Assert on text, the only backend-independent signal.
+ stale = [
+ h
+ for h in handle_retrieve_context({"query": "beta"})["results"]
+ if "beta" in (h.get("text") or "")
+ ]
+ self.assertEqual(stale, [])
+ self.assertTrue(handle_retrieve_context({"query": "gamma"})["results"])
+
+ removed = handle_remove_document({"source": "docS"})
+ self.assertEqual(removed["status"], "removed")
+ self.assertEqual(get_vector_store().count(), 0)
+
+ def test_sqlite_multi_document_isolation(self):
+ handle_store_document(
+ {
+ "content": make_doc("harbor", "vessel"),
+ "source": "nav_docs",
+ "authority": "official",
+ }
+ )
+ handle_store_document(
+ {
+ "content": make_doc("ledger", "invoice"),
+ "source": "fin_docs",
+ "authority": "draft",
+ "version": "v2",
+ }
+ )
+
+ nav = [
+ h
+ for h in handle_retrieve_context({"query": "vessel"})["results"]
+ if "vessel" in (h.get("text") or "")
+ ]
+ self.assertTrue(nav)
+ self.assertEqual(nav[0]["source"], "nav_docs")
+ self.assertEqual(nav[0]["authority"], "official")
+ self.assertEqual(nav[0]["status"], "active")
+ self.assertTrue(nav[0]["hash"])
+
+ # Updating one document must leave the other untouched.
+ updated = handle_update_document(
+ {"content": make_doc("anchor"), "source": "nav_docs"}
+ )
+ self.assertEqual(updated["status"], "updated")
+ fin = [
+ h
+ for h in handle_retrieve_context({"query": "invoice"})["results"]
+ if "invoice" in (h.get("text") or "")
+ ]
+ self.assertTrue(fin)
+ self.assertEqual(fin[0]["source"], "fin_docs")
+ self.assertEqual(fin[0]["authority"], "draft")
+ vessel_stale = [
+ h
+ for h in handle_retrieve_context({"query": "vessel"})["results"]
+ if "vessel" in (h.get("text") or "")
+ ]
+ self.assertEqual(vessel_stale, [])
+
+ # Removing the other document must leave the first intact.
+ removed = handle_remove_document({"source": "fin_docs", "version": "v2"})
+ self.assertEqual(removed["status"], "removed")
+ anchor = [
+ h
+ for h in handle_retrieve_context({"query": "anchor"})["results"]
+ if "anchor" in (h.get("text") or "")
+ ]
+ self.assertTrue(anchor and anchor[0]["source"] == "nav_docs")
+ ledger_stale = [
+ h
+ for h in handle_retrieve_context({"query": "ledger"})["results"]
+ if "ledger" in (h.get("text") or "")
+ ]
+ self.assertEqual(ledger_stale, [])
+
+ def test_sqlite_update_rolls_back_on_write_failure(self):
+ # Persistent path: removal is a direct delete_vectors, so the
+ # rollback has to re-store the snapshotted rows (plain lists,
+ # not arrays) when the new write fails.
+ handle_store_document(
+ {
+ "content": make_doc("oldterm", "legacy"),
+ "source": "handbook",
+ "authority": "official",
+ }
+ )
+ store = get_vector_store()
+ real_store_vectors = store.store_vectors
+
+ def failing_write(vectors, metas):
+ if any("phoenix" in (m.get("text") or "") for m in metas):
+ raise RuntimeError("simulated write failure")
+ return real_store_vectors(vectors, metas)
+
+ with patch.object(store, "store_vectors", side_effect=failing_write):
+ result = handle_update_document(
+ {"content": make_doc("phoenix"), "source": "handbook"}
+ )
+ self.assertIn("error", result)
+ self.assertEqual(get_vector_store().count(), 2)
+ old = [
+ h
+ for h in handle_retrieve_context({"query": "oldterm"})["results"]
+ if "oldterm" in (h.get("text") or "")
+ ]
+ self.assertTrue(old and old[0]["source"] == "handbook")
+
+ def test_sqlite_without_db_path_raises(self):
+ os.environ.pop("SEMANTICA_VECTOR_DB_PATH", None)
+ with self.assertRaises(ValueError):
+ get_vector_store()
+
+
+class TestPersistence(InmemoryBackendTestBase):
+ def test_store_persists_and_reloads(self):
+ tmpdir = tempfile.mkdtemp(prefix="semantica_vec_test_")
+ try:
+ os.environ["SEMANTICA_VECTOR_PATH"] = tmpdir
+ result = handle_store_document(
+ {"content": make_doc("persist"), "source": "docP", "authority": "official"}
+ )
+ self.assertTrue(result["persisted"])
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "store_data.json")))
+
+ # Fresh session state: the store must reload from disk.
+ reset_vector_store()
+ hits = handle_retrieve_context({"query": "persist"})["results"]
+ self.assertTrue(hits and "persist" in hits[0]["text"])
+ self.assertEqual(hits[0]["source"], "docP")
+ finally:
+ import shutil
+
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+ def test_persist_failure_is_reported_not_silent(self):
+ tmpdir = tempfile.mkdtemp(prefix="semantica_vec_test_")
+ try:
+ os.environ["SEMANTICA_VECTOR_PATH"] = tmpdir
+ store = get_vector_store()
+ with patch.object(store, "save", side_effect=RuntimeError("disk full")):
+ result = handle_store_document(
+ {"content": make_doc("volatile"), "source": "docV", "authority": "official"}
+ )
+ # The write itself succeeded; only the durable copy failed.
+ self.assertEqual(result["status"], "stored")
+ self.assertFalse(result["persisted"])
+ finally:
+ import shutil
+
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+ def test_reload_dimension_mismatch_rejected(self):
+ tmpdir = tempfile.mkdtemp(prefix="semantica_vec_test_")
+ try:
+ os.environ["SEMANTICA_VECTOR_PATH"] = tmpdir
+ handle_store_document(
+ {"content": make_doc("persist"), "source": "docP", "authority": "official"}
+ )
+ # A different embedder dimension must not silently rank
+ # vectors from an incompatible embedding space.
+ session._embedder = FakeEmbedder(32)
+ reset_vector_store()
+ with self.assertRaises(ValueError) as ctx:
+ get_vector_store()
+ self.assertIn("dimension", str(ctx.exception))
+ finally:
+ import shutil
+
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+ def test_corrupt_store_fails_on_startup(self):
+ """A broken persisted store must raise immediately, not silently
+ fall back to an empty store that would overwrite the user's data
+ on the first persist."""
+ tmpdir = tempfile.mkdtemp(prefix="semantica_vec_test_")
+ try:
+ # Drop a file that looks like a store directory but won't load.
+ with open(os.path.join(tmpdir, "store_data.json"), "w") as f:
+ f.write("{not valid json")
+ os.environ["SEMANTICA_VECTOR_PATH"] = tmpdir
+ reset_vector_store()
+ with self.assertRaises(ValueError) as ctx:
+ get_vector_store()
+ self.assertIn("Could not load", str(ctx.exception))
+ finally:
+ import shutil
+
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+if __name__ == "__main__":
+ unittest.main()