Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(symphony): 异常未抛出

chunbs_cbsff5e8ef102c3
diff --git a/jiuwenswarm/symphony/experience/bank.py b/jiuwenswarm/symphony/experience/bank.py
index dd39453451..5b95ec6abb 100644
--- a/jiuwenswarm/symphony/experience/bank.py
+++ b/jiuwenswarm/symphony/experience/bank.py
@@ -34,6 +34,7 @@ class _KnowledgeMeta:
vector_dimension: int = 0
vector_sha256: str = ""
scalar_sha256: str = ""
+ embeddings_sha256: str = ""
def _win_retry(func, retries: int = 3, delay: float = 0.1):
@@ -64,11 +65,11 @@ def _build_faiss_index(algorithm: str, dim: int) -> tuple[faiss.Index, str]:
index = faiss.index_factory(dim, algorithm, faiss.METRIC_INNER_PRODUCT)
except (RuntimeError, ValueError) as exc:
LOGGER.warning(
- "ExperienceBank: index_factory failed for '%s' (dim=%d): %s, falling back to Flat",
+ "ExperienceBank: index_factory failed for '%s' (dim=%d): %s",
algorithm, dim, exc,
+ exc_info=True,
)
- index = faiss.index_factory(dim, "Flat", faiss.METRIC_INNER_PRODUCT)
- actual_algorithm = "Flat"
+ raise
# IVF-style indices need training before adding vectors
if isinstance(index, faiss.IndexIVF):
@@ -84,9 +85,11 @@ def _write_atomic(source: Path, target: Path) -> None:
try:
_win_retry(lambda: os.replace(str(source), str(target)), retries=5, delay=0.2)
except FileNotFoundError:
- LOGGER.debug("_write_atomic: source=%s, target=%s — file vanished/locked during replace", source, target)
+ LOGGER.warning("_write_atomic: source, target file vanished/locked during replace")
+ raise
except Exception:
LOGGER.warning("_write_atomic failed", exc_info=True)
+ raise
class ExperienceBank:
@@ -146,7 +149,7 @@ class ExperienceBank:
self._id_index[item.id] = item
self._skills.add(frozenset(item.skill_ids))
self._rebuild_index()
- self.persist()
+ self._persist()
def add_batch(self, items: list[ExperienceItem]) -> None:
"""Add multiple items at once, rebuilding index and persisting only once."""
@@ -158,7 +161,7 @@ class ExperienceBank:
self._id_index[item.id] = item
self._skills.add(frozenset(item.skill_ids))
self._rebuild_index()
- self.persist()
+ self._persist()
def remove(self, item_id: str) -> bool:
"""Remove an item by id. Returns True if found and removed."""
@@ -169,7 +172,7 @@ class ExperienceBank:
self._items = [i for i in self._items if i.id != item_id]
self._skills.discard(frozenset(item.skill_ids))
self._rebuild_index()
- self.persist()
+ self._persist()
return True
# ------------------------------------------------------------------
@@ -227,42 +230,49 @@ class ExperienceBank:
# ------------------------------------------------------------------
def _load(self) -> None:
- if not self._dir.exists():
- LOGGER.info("ExperienceBank: index directory does not exist, starting empty")
- return
-
meta_path = self._dir / _META_FILE
scalar_path = self._dir / _SCALAR_DIR / _SCALAR_FILE
- faiss_path = self._dir / _VECTOR_DIR / _FAISS_FILE
- emb_path = self._dir / _VECTOR_DIR / _EMBED_FILE
+ vector_dir = self._dir / _VECTOR_DIR
+ faiss_path = vector_dir / _FAISS_FILE
+ emb_path = vector_dir / _EMBED_FILE
- if not meta_path.exists():
- LOGGER.error("ExperienceBank: integrity manifest (meta.json) is missing, starting empty")
- return
+ meta_exists = meta_path.exists()
+ scalar_exists = scalar_path.exists()
+ faiss_exist = faiss_path.exists()
+ emb_exists = emb_path.exists()
- if not scalar_path.exists():
- LOGGER.error("ExperienceBank: scalar metadata file does not exist, starting empty")
+ if not any([meta_exists, scalar_exists, faiss_exist, emb_exists]):
+ LOGGER.info("ExperienceBank: index directory is empty, starting empty")
return
- # --- integrity check ---
+ if not meta_exists:
+ raise FileNotFoundError(
+ f"ExperienceBank: meta.json missing but other index files present"
+ )
+ if not scalar_exists:
+ raise FileNotFoundError(
+ f"ExperienceBank: scalar/metadata.jsonl missing but other index files present "
+ )
+ if not faiss_path.exists():
+ raise FileNotFoundError(
+ f"ExperienceBank: vector/{_FAISS_FILE} missing but other index files present"
+ )
+ if not emb_path.exists():
+ raise FileNotFoundError(
+ f"ExperienceBank: vector/{_EMBED_FILE} missing but other index files present"
+ )
+
try:
meta_data = json.loads(meta_path.read_text(encoding="utf-8"))
meta = _KnowledgeMeta(**meta_data)
-
- scalar_actual = _sha256_file(scalar_path)
- if meta.scalar_sha256 and scalar_actual != meta.scalar_sha256:
- LOGGER.warning(
- "ExperienceBank: scalar integrity check failed, loading anyway (debug mode)"
- )
-
- if faiss_path.exists():
- faiss_actual = _sha256_file(faiss_path)
- if meta.vector_sha256 and faiss_actual != meta.vector_sha256:
- LOGGER.warning(
- "ExperienceBank: vector integrity check failed, loading anyway (debug mode)"
- )
except Exception as exc:
- LOGGER.error("ExperienceBank: failed to parse manifest, skipping check")
+ LOGGER.error("ExperienceBank: failed to parse manifest: %s", exc, exc_info=True)
+ raise
+
+ if not self._validate_hashes(meta, scalar_path, faiss_path, emb_path):
+ raise ValueError(
+ "ExperienceBank: integrity check failed — manifest does not match on-disk files"
+ )
try:
# 1. Load scalar metadata
@@ -278,38 +288,25 @@ class ExperienceBank:
self._skills.add(frozenset(item.skill_ids))
# 2. Load embeddings matrix and re-hydrate in-memory items
- if emb_path.exists():
- self._embedding_matrix = np.load(str(emb_path))
- # Re-normalize to ensure IndexFlatIP inner product = cosine similarity
- if self._embedding_matrix is not None and len(self._embedding_matrix) > 0:
- norms = np.linalg.norm(self._embedding_matrix, axis=1, keepdims=True)
- norms[norms == 0] = 1.0
- self._embedding_matrix = self._embedding_matrix / norms
- for i, item in enumerate(self._items):
- if i < len(self._embedding_matrix):
- item.embedding = self._embedding_matrix[i].tolist()
+ self._embedding_matrix = np.load(str(emb_path))
+ # Re-normalize to ensure IndexFlatIP inner product = cosine similarity
+ if self._embedding_matrix is not None and len(self._embedding_matrix) > 0:
+ norms = np.linalg.norm(self._embedding_matrix, axis=1, keepdims=True)
+ norms[norms == 0] = 1.0
+ self._embedding_matrix = self._embedding_matrix / norms
+ for i, item in enumerate(self._items):
+ if i < len(self._embedding_matrix):
+ item.embedding = self._embedding_matrix[i].tolist()
# 3. Load FAISS index
- if faiss_path.exists():
- self._faiss_index = faiss.read_index(str(faiss_path))
-
- # 4. Validate vector count against manifest
- if meta.vector_count and meta.vector_count != len(self._items):
- LOGGER.warning(
- "ExperienceBank: vector_count mismatch: manifest says %d, loaded %d",
- meta.vector_count, len(self._items),
- )
+ self._faiss_index = faiss.read_index(str(faiss_path))
- # 4b. Validate vector dimension against manifest
- if meta.vector_dimension and self._embedding_matrix is not None:
- actual_dim = self._embedding_matrix.shape[1]
- if meta.vector_dimension != actual_dim:
- LOGGER.warning(
- "ExperienceBank: vector_dimension mismatch: manifest says %d, actual %d",
- meta.vector_dimension, actual_dim,
- )
+ if not self._validate_counts(meta):
+ raise ValueError(
+ "ExperienceBank: integrity check failed — manifest counts do not match loaded data"
+ )
- # 5. Initialize ID counter from max existing ID
+ # 4. Initialize ID counter from max existing ID
if self._items:
max_id = 0
for item in self._items:
@@ -317,64 +314,169 @@ class ExperienceBank:
try:
num = int(item.id.split("_")[1])
max_id = max(max_id, num)
- except (IndexError, ValueError):
- pass
+ except (IndexError, ValueError) as exc:
+ LOGGER.warning(
+ "ExperienceBank: malformed item id %r while initializing id counter: %s",
+ item.id, exc,
+ exc_info=True,
+ )
+ raise
self._next_id_counter = max_id + 1
LOGGER.info("ExperienceBank: loaded %d items", len(self._items))
except Exception as exc:
- LOGGER.error("ExperienceBank: failed to load data: %s", exc)
+ LOGGER.error("ExperienceBank: failed to load data: %s", exc, exc_info=True)
+ raise
+
+
+ @staticmethod
+ def _validate_hashes(
+ meta: _KnowledgeMeta,
+ scalar_path: Path,
+ faiss_path: Path,
+ emb_path: Path,
+ ) -> bool:
+ """Return True iff the manifest declares all three sha256 values
+ and each matches the corresponding on-disk file.
+
+ All three fields (scalar_sha256, vector_sha256, embeddings_sha256)
+ MUST be non-empty and MUST hash-match their files. An empty field
+ is treated as a corrupt/missing manifest entry — return False.
+ File existence is already enforced by ``_load``'s pre-check.
+ """
+ if not meta.scalar_sha256:
+ LOGGER.error("ExperienceBank: manifest missing scalar_sha256")
+ return False
+ scalar_actual = _sha256_file(scalar_path)
+ if scalar_actual != meta.scalar_sha256:
+ LOGGER.error("ExperienceBank: scalar sha256 mismatch")
+ return False
+
+ if not meta.vector_sha256:
+ LOGGER.error("ExperienceBank: manifest missing vector_sha256")
+ return False
+ faiss_actual = _sha256_file(faiss_path)
+ if faiss_actual != meta.vector_sha256:
+ LOGGER.error("ExperienceBank: faiss sha256 mismatch")
+ return False
+
+ if not meta.embeddings_sha256:
+ LOGGER.error("ExperienceBank: manifest missing embeddings_sha256")
+ return False
+ emb_actual = _sha256_file(emb_path)
+ if emb_actual != meta.embeddings_sha256:
+ LOGGER.error("ExperienceBank: embeddings sha256 mismatch")
+ return False
+
+ return True
+
+ def _validate_counts(self, meta: _KnowledgeMeta) -> bool:
+ """Return True iff loaded in-memory data matches the manifest counts.
+
+ Runs after scalar + embedding data is loaded — compares against
+ ``self._items`` and ``self._embedding_matrix``. The manifest's
+ ``vector_count`` must equal BOTH the number of loaded items AND
+ the number of embedding rows; a mismatch between items and
+ embedding rows (even if both are non-zero) is also a failure.
+ """
+ if meta.vector_count != len(self._items):
+ LOGGER.error(
+ "ExperienceBank: vector_count mismatch — manifest=%d, items=%d",
+ meta.vector_count, len(self._items),
+ )
+ return False
+ if self._embedding_matrix is None:
+ LOGGER.error("ExperienceBank: embeddings matrix not loaded")
+ return False
+ if len(self._embedding_matrix) != meta.vector_count:
+ LOGGER.error(
+ "ExperienceBank: embedding row count mismatch — manifest=%d, rows=%d",
+ meta.vector_count, len(self._embedding_matrix),
+ )
+ return False
+
+ if meta.vector_dimension and self._embedding_matrix is not None:
+ actual_dim = self._embedding_matrix.shape[1]
+ if meta.vector_dimension != actual_dim:
+ LOGGER.error(
+ "ExperienceBank: vector_dimension mismatch — manifest=%d, actual=%d",
+ meta.vector_dimension, actual_dim,
+ )
+ return False
+
+ return True
- def persist(self) -> None:
- """Persist to index_dir with integrity manifest."""
+
+ def _persist(self) -> None:
+ """Persist to index_dir atomically with an integrity manifest."""
# Ensure root directory exists first
+
+ if self._faiss_index is None or self._embedding_matrix is None:
+ LOGGER.error("faiss index or embedding matrix is None")
+ return
self._dir.mkdir(parents=True, exist_ok=True)
scalar_dir = self._dir / _SCALAR_DIR
- scalar_path = scalar_dir / _SCALAR_FILE
vector_dir = self._dir / _VECTOR_DIR
-
scalar_dir.mkdir(parents=True, exist_ok=True)
vector_dir.mkdir(parents=True, exist_ok=True)
- # 1. Write scalar/metadata.jsonl
+ scalar_path = scalar_dir / _SCALAR_FILE
+ faiss_path = vector_dir / _FAISS_FILE
+ emb_path = vector_dir / _EMBED_FILE
+
tmp_scalar = scalar_dir / (_SCALAR_FILE + ".tmp")
- with open(tmp_scalar, "w", encoding="utf-8") as f:
- for item in self._items:
- f.write(json.dumps(item.to_dict(), ensure_ascii=False) + "\n")
- _write_atomic(tmp_scalar, scalar_path)
-
- # 2. Write vector/faiss_index.bin
- if self._faiss_index is not None:
- faiss_path = vector_dir / _FAISS_FILE
- tmp_faiss = vector_dir / "faiss_tmp"
- faiss.write_index(self._faiss_index, str(tmp_faiss))
- _write_atomic(tmp_faiss, faiss_path)
+ tmp_faiss = vector_dir / "faiss_tmp"
- # 3. Write vector/embeddings.npy
- # np.save appends ".npy" automatically, so we write to "embed_tmp"
- # which produces "embed_tmp.npy", then rename to "embeddings.npy".
- if self._embedding_matrix is not None:
- emb_path = vector_dir / _EMBED_FILE
- tmp_emb = vector_dir / "embed_tmp"
- np.save(str(tmp_emb), self._embedding_matrix)
- _write_atomic(tmp_emb.with_suffix(".npy"), emb_path)
-
- # 4. Write meta.json (integrity manifest)
- dim = self._embedding_matrix.shape[1] if self._embedding_matrix is not None else 0
- meta = _KnowledgeMeta(
- vector_count=len(self._items),
- vector_algorithm=self._vector_algorithm,
- vector_dimension=dim,
- vector_sha256=_sha256_file(vector_dir / _FAISS_FILE) if self._faiss_index is not None else "",
- scalar_sha256=_sha256_file(scalar_path),
- )
+ tmp_emb_src = vector_dir / "embed_tmp"
+ tmp_emb = tmp_emb_src.with_suffix(".npy")
tmp_meta = self._dir / (_META_FILE + ".tmp")
- tmp_meta.write_text(
- json.dumps(meta.__dict__, ensure_ascii=False, indent=2) + "\n",
- encoding="utf-8",
- )
- _write_atomic(tmp_meta, self._dir / _META_FILE)
+
+ written_tmps: list[Path] = []
+ try:
+ with open(tmp_scalar, "w", encoding="utf-8") as f:
+ for item in self._items:
+ f.write(json.dumps(item.to_dict(), ensure_ascii=False) + "\n")
+ written_tmps.append(tmp_scalar)
+
+
+ faiss.write_index(self._faiss_index, str(tmp_faiss))
+ written_tmps.append(tmp_faiss)
+
+
+ np.save(str(tmp_emb_src), self._embedding_matrix)
+ written_tmps.append(tmp_emb)
+
+ dim = self._embedding_matrix.shape[1] if self._embedding_matrix is not None else 0
+ meta = _KnowledgeMeta(
+ vector_count=len(self._items),
+ vector_algorithm=self._vector_algorithm,
+ vector_dimension=dim,
+ vector_sha256=_sha256_file(tmp_faiss),
+ scalar_sha256=_sha256_file(tmp_scalar),
+ embeddings_sha256=_sha256_file(tmp_emb),
+ )
+ tmp_meta.write_text(
+ json.dumps(meta.__dict__, ensure_ascii=False, indent=2) + "\n",
+ encoding="utf-8",
+ )
+ written_tmps.append(tmp_meta)
+
+ _write_atomic(tmp_faiss, faiss_path)
+ _write_atomic(tmp_emb, emb_path)
+ _write_atomic(tmp_scalar, scalar_path)
+ _write_atomic(tmp_meta, self._dir / _META_FILE)
+ except Exception:
+ LOGGER.error(
+ "ExperienceBank: persist failed, cleaning up temp files",
+ exc_info=True,
+ )
+ for p in written_tmps:
+ try:
+ p.unlink(missing_ok=True)
+ except OSError:
+ LOGGER.warning("ExperienceBank: failed to clean up temp file", exc_info=True)
+ raise
# ------------------------------------------------------------------
# Index management
diff --git a/jiuwenswarm/symphony/experience/cluster.py b/jiuwenswarm/symphony/experience/cluster.py
index ca925766ff..525427d22b 100644
--- a/jiuwenswarm/symphony/experience/cluster.py
+++ b/jiuwenswarm/symphony/experience/cluster.py
@@ -144,7 +144,7 @@ def _faiss_cluster(
try:
import faiss
except ImportError:
- LOGGER.debug("FAISS not available, falling back to single-cluster")
+ LOGGER.warning("FAISS not available, falling back to single-cluster")
return [0] * n
# Normalize vectors for inner-product = cosine similarity
diff --git a/jiuwenswarm/symphony/experience/distiller.py b/jiuwenswarm/symphony/experience/distiller.py
index a0c89e3e46..db4946d77b 100644
--- a/jiuwenswarm/symphony/experience/distiller.py
+++ b/jiuwenswarm/symphony/experience/distiller.py
@@ -110,6 +110,10 @@ class TraceDistiller:
idx, clusters[idx].cluster_id, exc,
type(exc).__name__, exc,
)
+ raise RuntimeError(
+ f"TraceDistiller: distillation failed for cluster {idx} "
+ f"(id={clusters[idx].cluster_id}): {exc}"
+ ) from exc
return [r for r in results if r is not None]
diff --git a/tests/symphony/test_experience_base.py b/tests/symphony/test_experience_base.py
index 975d2bd195..40d3f07ead 100644
--- a/tests/symphony/test_experience_base.py
+++ b/tests/symphony/test_experience_base.py
@@ -11,7 +11,9 @@ from __future__ import annotations
from typing import Any
import numpy as np
+import pytest
+from jiuwenswarm.symphony.experience.bank import ExperienceBank
from jiuwenswarm.symphony.experience.cluster import ClusteredQuery, cluster_traces
from jiuwenswarm.symphony.experience.collector import ExperienceBaseBuilder
from jiuwenswarm.symphony.experience.retriever import ExperienceRetriever
@@ -350,6 +352,49 @@ def test_add_accepts_valid_trace() -> None:
assert len(builder._pending) == 1
+def test_add_propagates_flush_exception_instead_of_dropping_pending(monkeypatch) -> None:
+ """When the LLM is down, distiller.run() must surface the error from
+ add()'s auto-flush rather than silently clearing the pending buffer.
+
+ Regression: distiller.run used to log-and-drop per-cluster exceptions,
+ return [], and let flush_snapshot report created=0 — the pending
+ snapshot had already been cleared by add(), so the data was lost
+ without any signal to the caller.
+ """
+ import threading
+
+ class _BoomDistiller:
+ def run(self, _clusters: list[Any]) -> list[DistilledPattern]:
+ raise RuntimeError("LLM unavailable")
+
+ builder = ExperienceBaseBuilder.__new__(ExperienceBaseBuilder)
+ builder._pending = []
+ builder._flush_threshold = 1
+ builder._lock = threading.Lock()
+ builder._min_hits = 1
+ builder._skill_cluster_num = None
+ builder._min_cluster_size = 1
+ builder._cluster_max_examples = None
+ builder._embedder = FakeEmbedder({"q": [1.0, 0.0]})
+ builder._kb = FakeBank()
+ builder._skills_info = None
+ builder._max_workers = 1
+ builder._max_success_examples = 1
+ builder._pattern_merge_threshold = 1.0
+ builder._query_examples_count = 0
+
+ import jiuwenswarm.symphony.experience.collector as collector_mod
+ monkeypatch.setattr(
+ collector_mod, "TraceDistiller",
+ lambda *a, **kw: _BoomDistiller(),
+ )
+
+ trace = TraceRecord(trace_id="t1", query="q", skills=["s"], success=True)
+ with pytest.raises(Exception):
+ builder.add(trace)
+ assert builder._pending == [], "auto-flush failure should still leave pending cleared by add()"
+
+
def test_retriever_dedups_shared_skills_preserving_similarity_order() -> None:
# Two items, both referencing skill "s1"; the higher-score item also
# carries "s2". Without dedup the flat comprehension would yield
@@ -408,4 +453,323 @@ def test_retriever_dedups_repeated_skills_within_a_single_item() -> None:
assert out == ["s1", "s2", "s3"]
for skill in ("s1", "s2", "s3"):
- assert out.count(skill) == 1
\ No newline at end of file
+ assert out.count(skill) == 1
+
+
+def test_load_raises_on_corrupt_meta_json(tmp_path) -> None:
+ """When meta.json cannot be parsed, ExperienceBank._load must surface
+ the error rather than swallow it.
+
+ Regression: the integrity-check try/except used to log "failed to parse
+ manifest, skipping check" and fall through with ``meta`` unbound, so
+ the downstream ``meta.vector_count`` reference raised
+ ``UnboundLocalError`` — masked by the data-load try/except as
+ "failed to load data: cannot access local variable 'meta'". Both
+ except blocks now log and re-raise; construction fails fast.
+ """
+ import json
+
+ (tmp_path / "meta.json").write_text("{ not valid json", encoding="utf-8")
+ scalar_dir = tmp_path / "scalar"
+ scalar_dir.mkdir(parents=True, exist_ok=True)
+ (scalar_dir / "metadata.jsonl").write_text(
+ json.dumps({
+ "id": "exp_0001",
+ "query_pattern": "p",
+ "query_examples": [],
+ "skill_ids": ["s"],
+ "success_count": 1,
+ "created_at": 0.0,
+ "last_hit_at": 0.0,
+ "embedding": [],
+ }) + "\n",
+ encoding="utf-8",
+ )
+
+ embedder = FakeEmbedder({"p": [1.0, 0.0]})
+
+ with pytest.raises(Exception):
+ ExperienceBank(tmp_path, embedder)
+
+
+def test_load_starts_empty_when_all_index_files_absent(tmp_path) -> None:
+ """Empty-start contract: when meta.json, scalar/, and vector/ are all
+ absent, the bank starts empty instead of raising."""
+ embedder = FakeEmbedder({"p": [1.0, 0.0]})
+
+ kb = ExperienceBank(tmp_path, embedder)
+
+ assert kb.count == 0
+ assert kb.items == []
+
+
+def test_load_succeeds_with_valid_manifest_and_data(tmp_path) -> None:
+ """Valid manifest + scalar/vector data with matching SHA256 loads cleanly."""
+ import hashlib
+ import json
+
+ import faiss
+ import numpy as np
+
+ scalar_dir = tmp_path / "scalar"
+ scalar_dir.mkdir(parents=True, exist_ok=True)
+ scalar_path = scalar_dir / "metadata.jsonl"
+ (scalar_path).write_text(
+ json.dumps({
+ "id": "exp_0001",
+ "query_pattern": "p",
+ "query_examples": [],
+ "skill_ids": ["s"],
+ "success_count": 1,
+ "created_at": 0.0,
+ "last_hit_at": 0.0,
+ "embedding": [1.0, 0.0],
+ }) + "\n",
+ encoding="utf-8",
+ )
+
+ vector_dir = tmp_path / "vector"
+ vector_dir.mkdir(parents=True, exist_ok=True)
+ emb_path = vector_dir / "embeddings.npy"
+ faiss_path = vector_dir / "faiss_index.bin"
+
+ arr = np.array([[1.0, 0.0]], dtype=np.float32)
+ np.save(str(emb_path.with_suffix("")), arr)
+ index = faiss.index_factory(2, "Flat", faiss.METRIC_INNER_PRODUCT)
+ index.add(arr)
+ faiss.write_index(index, str(faiss_path))
+
+ scalar_sha = hashlib.sha256(scalar_path.read_bytes()).hexdigest()
+ emb_sha = hashlib.sha256(emb_path.read_bytes()).hexdigest()
+ faiss_sha = hashlib.sha256(faiss_path.read_bytes()).hexdigest()
+ (tmp_path / "meta.json").write_text(
+ json.dumps({
+ "version": 1,
+ "vector_count": 1,
+ "vector_algorithm": "Flat",
+ "vector_dimension": 2,
+ "vector_sha256": faiss_sha,
+ "scalar_sha256": scalar_sha,
+ "embeddings_sha256": emb_sha,
+ }),
+ encoding="utf-8",
+ )
+ embedder = FakeEmbedder({"p": [1.0, 0.0]})
+
+ kb = ExperienceBank(tmp_path, embedder)
+
+ assert kb.count == 1
+
+
+ "write_meta, write_scalar, write_faiss, write_embeddings, expected_exc",
+ [
+ (True, False, False, False, Exception),
+ (False, True, False, False, Exception),
+ (True, True, False, True, FileNotFoundError),
+ (True, True, True, False, FileNotFoundError),
+ ],
+)
+def test_load_raises_when_partial_state_present(
+ tmp_path, write_meta, write_scalar, write_faiss, write_embeddings, expected_exc,
+) -> None:
+ """Any partial on-disk state (some index files present, others absent)
+ must raise rather than silently load incomplete data.
+
+ Parametrized over the four "which file is missing" precheck branches.
+ """
+ import json
+
+ if write_scalar:
+ scalar_dir = tmp_path / "scalar"
+ scalar_dir.mkdir(parents=True, exist_ok=True)
+ (scalar_dir / "metadata.jsonl").write_text(
+ json.dumps({
+ "id": "exp_0001",
+ "query_pattern": "p",
+ "query_examples": [],
+ "skill_ids": ["s"],
+ "success_count": 1,
+ "created_at": 0.0,
+ "last_hit_at": 0.0,
+ "embedding": [1.0, 0.0],
+ }) + "\n",
+ encoding="utf-8",
+ )
+ if write_faiss or write_embeddings:
+ vector_dir = tmp_path / "vector"
+ vector_dir.mkdir(parents=True, exist_ok=True)
+ if write_embeddings:
+ import numpy as np
+ np.save(
+ str(vector_dir / "embeddings.npy"),
+ np.array([[1.0, 0.0]], dtype=np.float32),
+ )
+ if write_faiss:
+ import faiss
+ import numpy as np
+ arr = np.array([[1.0, 0.0]], dtype=np.float32)
+ index = faiss.index_factory(2, "Flat", faiss.METRIC_INNER_PRODUCT)
+ index.add(arr)
+ faiss.write_index(index, str(vector_dir / "faiss_index.bin"))
+ if write_meta:
+ (tmp_path / "meta.json").write_text(
+ json.dumps({
+ "version": 1,
+ "vector_count": 1,
+ "vector_algorithm": "Flat",
+ "vector_dimension": 2,
+ "vector_sha256": "",
+ "scalar_sha256": "",
+ "embeddings_sha256": "",
+ }),
+ encoding="utf-8",
+ )
+
+ embedder = FakeEmbedder({"p": [1.0, 0.0]})
+
+ with pytest.raises(expected_exc):
+ ExperienceBank(tmp_path, embedder)
+
+
+ "manifest_overrides, expected_exc",
+ [
+ ({"scalar_sha256": "deadbeef" * 8}, Exception),
+ ({"embeddings_sha256": "deadbeef" * 8}, Exception),
+ ({"scalar_sha256": ""}, Exception),
+ ({"vector_count": 1}, Exception),
+ ],
+)
+def test_load_raises_when_manifest_field_invalid(
+ tmp_path, manifest_overrides, expected_exc,
+) -> None:
+ """A full valid on-disk index whose manifest declares one corrupted
+ sha256 / count field must raise. Parametrized over the four integrity
+ failures: scalar hash mismatch, embeddings hash mismatch, empty
+ scalar_sha256, and embedding row count != vector_count.
+ """
+ import hashlib
+ import json
+
+ import faiss
+ import numpy as np
+
+ scalar_dir = tmp_path / "scalar"
+ scalar_dir.mkdir(parents=True, exist_ok=True)
+ scalar_path = scalar_dir / "metadata.jsonl"
+ (scalar_path).write_text(
+ json.dumps({
+ "id": "exp_0001",
+ "query_pattern": "p",
+ "query_examples": [],
+ "skill_ids": ["s"],
+ "success_count": 1,
+ "created_at": 0.0,
+ "last_hit_at": 0.0,
+ "embedding": [1.0, 0.0],
+ }) + "\n",
+ encoding="utf-8",
+ )
+
+ vector_dir = tmp_path / "vector"
+ vector_dir.mkdir(parents=True, exist_ok=True)
+ emb_path = vector_dir / "embeddings.npy"
+ faiss_path = vector_dir / "faiss_index.bin"
+
+ # Two-row embedding matrix — used by the row-count-mismatch scenario;
+ # other scenarios override vector_count to match.
+ arr = np.array([[1.0, 0.0], [0.0, 1.0]], dtype=np.float32)
+ np.save(str(emb_path), arr)
+ index = faiss.index_factory(2, "Flat", faiss.METRIC_INNER_PRODUCT)
+ index.add(arr)
+ faiss.write_index(index, str(faiss_path))
+
+ scalar_sha = hashlib.sha256(scalar_path.read_bytes()).hexdigest()
+ emb_sha = hashlib.sha256(emb_path.read_bytes()).hexdigest()
+ faiss_sha = hashlib.sha256(faiss_path.read_bytes()).hexdigest()
+ base_manifest = {
+ "version": 1,
+ "vector_count": 2,
+ "vector_algorithm": "Flat",
+ "vector_dimension": 2,
+ "vector_sha256": faiss_sha,
+ "scalar_sha256": scalar_sha,
+ "embeddings_sha256": emb_sha,
+ }
+ base_manifest.update(manifest_overrides)
+ (tmp_path / "meta.json").write_text(
+ json.dumps(base_manifest),
+ encoding="utf-8",
+ )
+ embedder = FakeEmbedder({"p": [1.0, 0.0]})
+
+ with pytest.raises(expected_exc):
+ ExperienceBank(tmp_path, embedder)
+
+
+def test_load_raises_on_scalar_sha256_mismatch(tmp_path) -> None:
+ """Scalar file SHA256 mismatch must raise.
+
+ Dedicated regression for the ``_validate_hashes`` scalar branch
+ (bank.py: scalar_actual != meta.scalar_sha256). Builds a fully valid
+ on-disk index where ``vector_sha256`` and ``embeddings_sha256`` are
+ correct so the validator reaches the scalar comparison rather than
+ short-circuiting on an empty/invalid vector hash first — and only the
+ scalar hash is corrupted.
+ """
+ import hashlib
+ import json
+
+ import faiss
+ import numpy as np
+
+ scalar_dir = tmp_path / "scalar"
+ scalar_dir.mkdir(parents=True, exist_ok=True)
+ scalar_path = scalar_dir / "metadata.jsonl"
+ (scalar_path).write_text(
+ json.dumps({
+ "id": "exp_0001",
+ "query_pattern": "p",
+ "query_examples": [],
+ "skill_ids": ["s"],
+ "success_count": 1,
+ "created_at": 0.0,
+ "last_hit_at": 0.0,
+ "embedding": [1.0, 0.0],
+ }) + "\n",
+ encoding="utf-8",
+ )
+
+ vector_dir = tmp_path / "vector"
+ vector_dir.mkdir(parents=True, exist_ok=True)
+ emb_path = vector_dir / "embeddings.npy"
+ faiss_path = vector_dir / "faiss_index.bin"
+
+ arr = np.array([[1.0, 0.0]], dtype=np.float32)
+ np.save(str(emb_path), arr)
+ index = faiss.index_factory(2, "Flat", faiss.METRIC_INNER_PRODUCT)
+ index.add(arr)
+ faiss.write_index(index, str(faiss_path))
+
+ emb_sha = hashlib.sha256(emb_path.read_bytes()).hexdigest()
+ faiss_sha = hashlib.sha256(faiss_path.read_bytes()).hexdigest()
+ (tmp_path / "meta.json").write_text(
+ json.dumps({
+ "version": 1,
+ "vector_count": 1,
+ "vector_algorithm": "Flat",
+ "vector_dimension": 2,
+ # Correct — must not short-circuit the validator on the vector branch.
+ "vector_sha256": faiss_sha,
+ # Deliberately wrong — the scalar mismatch path under test.
+ "scalar_sha256": "deadbeef" * 8,
+ # Correct — must not short-circuit the validator on the embeddings branch.
+ "embeddings_sha256": emb_sha,
+ }),
+ encoding="utf-8",
+ )
+ embedder = FakeEmbedder({"p": [1.0, 0.0]})
+
+ with pytest.raises(Exception):
+ ExperienceBank(tmp_path, embedder)
\ No newline at end of file