diff --git a/mempalace/backends/sqlite_exact.py b/mempalace/backends/sqlite_exact.py
index 586f2fb..7c946f2 100644
--- a/mempalace/backends/sqlite_exact.py
+++ b/mempalace/backends/sqlite_exact.py
@@ -972,11 +972,12 @@ class SQLiteExactBackend(BaseBackend):
if cached is not None and not cached.closed:
if read_only and cached.immutable:
# An immutable snapshot freezes the clean-database view.
- # When a writer later creates WAL sidecars, keep serving
- # that snapshot only until both files exist, then reopen
- # with normal mode=ro so recall sees the writer's commits.
+ # Reopen only when the complete WAL sidecar pair is present
+ # (active writer). A partial pair is a transient mid-open
+ # state ā keep the immutable handle rather than forcing a
+ # reconnect that would raise on the incomplete set.
wal_exists, shm_exists = self._wal_sidecar_state(db_path)
- if wal_exists or shm_exists:
+ if wal_exists and shm_exists:
self._retire_read_only_handle(palace_path, cached)
cached = None
if cached is not None:
diff --git a/mempalace/convo_miner.py b/mempalace/convo_miner.py
index f0ec548..b6b714f 100644
--- a/mempalace/convo_miner.py
+++ b/mempalace/convo_miner.py
@@ -600,7 +600,11 @@ def _file_chunks_locked(
}
if source_mtime is not None:
meta["source_mtime"] = source_mtime
- if content_hash is not None:
+ # Stamp content_hash only on chunk 0 so multi-conversation
+ # privacy-export hashes are not O(N²)-duplicated across every
+ # chunk row. ``prefetch_content_hashes`` still finds them ā
+ # it scans all drawers and splits comma-joined hash fields.
+ if content_hash is not None and chunk.get("chunk_index", 0) == 0:
meta["content_hash"] = content_hash
batch_metas.append(meta)
assert_no_collisions(list(zip(batch_ids, batch_metas)), collection)
diff --git a/mempalace/palace.py b/mempalace/palace.py
index c9c1f7d..34e1804 100644
--- a/mempalace/palace.py
+++ b/mempalace/palace.py
@@ -235,15 +235,41 @@ def get_collection(
try:
collection = backend_obj.get_collection(**preferred_kwargs)
except TypeError as exc:
- if "unexpected keyword argument 'palace'" not in str(exc):
+ msg = str(exc)
+ # Plugin backends may still use the pre-options signature. Drop
+ # ``options`` first so read_only degrades gracefully instead of
+ # hard-failing TypeError on third-party entry points.
+ if backend_options is not None and "options" in msg:
+ preferred_kwargs.pop("options", None)
+ try:
+ collection = backend_obj.get_collection(**preferred_kwargs)
+ except TypeError as nested:
+ if "unexpected keyword argument 'palace'" not in str(nested):
+ raise
+ collection = backend_obj.get_collection(
+ palace_path,
+ collection_name=collection_name,
+ create=create,
+ )
+ elif "unexpected keyword argument 'palace'" not in msg:
raise
- legacy_kwargs = {
- "collection_name": collection_name,
- "create": create,
- }
- if backend_options is not None:
- legacy_kwargs["options"] = backend_options
- collection = backend_obj.get_collection(palace_path, **legacy_kwargs)
+ else:
+ legacy_kwargs = {
+ "collection_name": collection_name,
+ "create": create,
+ }
+ if backend_options is not None:
+ legacy_kwargs["options"] = backend_options
+ try:
+ collection = backend_obj.get_collection(palace_path, **legacy_kwargs)
+ except TypeError as nested:
+ if backend_options is None or "options" not in str(nested):
+ raise
+ collection = backend_obj.get_collection(
+ palace_path,
+ collection_name=collection_name,
+ create=create,
+ )
if "requires_explicit_embeddings" in getattr(backend_obj, "capabilities", frozenset()):
collection = EmbeddingCollection(collection)
if not _skip_identity_check:
diff --git a/mempalace/searcher.py b/mempalace/searcher.py
index 82b43f3..d4f051d 100644
--- a/mempalace/searcher.py
+++ b/mempalace/searcher.py
@@ -636,10 +636,10 @@ def _bm25_only_via_sqlite(
"""
db_path = os.path.join(palace_path, "chroma.sqlite3")
if not os.path.isfile(db_path):
- return {
- "error": "No palace found",
- "hint": "Run: mempalace init
&& mempalace mine ",
- }
+ return _search_error_result(
+ "No palace found",
+ hint="Run: mempalace init && mempalace mine ",
+ )
if collection_name is None:
from .config import get_configured_collection_name
@@ -673,7 +673,7 @@ def _bm25_only_via_sqlite(
try:
conn = sqlite3.connect(sqlite_read_uri(db_path), uri=True)
except sqlite3.Error as e:
- return {"error": f"sqlite open failed: {e}"}
+ return _search_error_result(f"sqlite open failed: {e}")
try:
# FTS5 MATCH expects whitespace-separated tokens. Drop tokens
@@ -1033,11 +1033,13 @@ def _finalize_candidate_hits(
source_file=source_file,
)
except UnsupportedCapabilityError:
- return [], {
- "error": "candidate_strategy='union' requires a backend with lexical_search support",
- "unsupported_capability": "supports_lexical_search",
- "hint": "Use candidate_strategy='vector' or select a backend that supports lexical search.",
- }
+ return [], _search_error_result(
+ "candidate_strategy='union' requires a backend with lexical_search support",
+ unsupported_capability="supports_lexical_search",
+ hint=(
+ "Use candidate_strategy='vector' or select a backend that supports lexical search."
+ ),
+ )
hits = _hybrid_rank(hits, query, metric=_metric_for_collection(drawers_col))[:n_results]
for h in hits:
@@ -1048,20 +1050,32 @@ def _finalize_candidate_hits(
return hits, None
+def _search_error_result(error: str, **extra) -> dict:
+ """Error envelope for programmatic search callers.
+
+ Always includes ``results: []`` so callers can safely index
+ ``result["results"]`` without a KeyError when the palace failed to
+ open or the query raised mid-flight (Windows CI flake surface).
+ """
+ out = {"error": error, "results": []}
+ out.update(extra)
+ return out
+
+
def _backend_mismatch_result(error: BackendMismatchError) -> dict:
- return {
- "error": "Backend mismatch",
- "details": str(error),
- "hint": "Select the matching backend or use a fresh palace directory.",
- }
+ return _search_error_result(
+ "Backend mismatch",
+ details=str(error),
+ hint="Select the matching backend or use a fresh palace directory.",
+ )
def _unknown_backend_result(error: KeyError) -> dict:
- return {
- "error": "Unknown backend",
- "details": str(error),
- "hint": "Check MEMPALACE_BACKEND or the configured backend name.",
- }
+ return _search_error_result(
+ "Unknown backend",
+ details=str(error),
+ hint="Check MEMPALACE_BACKEND or the configured backend name.",
+ )
def _vector_disabled_search(
@@ -1081,12 +1095,12 @@ def _vector_disabled_search(
except KeyError as e:
return _unknown_backend_result(e)
if backend_name != "chroma":
- return {
- "error": "vector_disabled fallback is Chroma-only",
- "unsupported_capability": "chroma_hnsw_fallback",
- "backend": backend_name,
- "hint": "Disable vector_disabled for non-Chroma backends.",
- }
+ return _search_error_result(
+ "vector_disabled fallback is Chroma-only",
+ unsupported_capability="chroma_hnsw_fallback",
+ backend=backend_name,
+ hint="Disable vector_disabled for non-Chroma backends.",
+ )
return _bm25_only_via_sqlite(
query,
palace_path,
@@ -1107,23 +1121,23 @@ def _open_search_collection(palace_path: str, collection_name: str):
return None, _unknown_backend_result(e)
except (CollectionNotInitializedError, PalaceNotFoundError) as e:
logger.error("No palace found at %s: %s", palace_path, e)
- return None, {
- "error": "No palace found",
- "hint": "Run: mempalace init && mempalace mine ",
- }
+ return None, _search_error_result(
+ "No palace found",
+ hint="Run: mempalace init && mempalace mine ",
+ )
except BackendError as e:
logger.error("Backend error opening palace at %s: %s", palace_path, e)
- return None, {
- "error": "Backend error",
- "details": str(e),
- "hint": "Check the selected backend configuration and availability.",
- }
+ return None, _search_error_result(
+ "Backend error",
+ details=str(e),
+ hint="Check the selected backend configuration and availability.",
+ )
except Exception as e:
logger.error("No palace found at %s: %s", palace_path, e)
- return None, {
- "error": "No palace found",
- "hint": "Run: mempalace init && mempalace mine ",
- }
+ return None, _search_error_result(
+ "No palace found",
+ hint="Run: mempalace init && mempalace mine ",
+ )
def _query_drawers_with_filter_fallback(
@@ -1273,7 +1287,7 @@ def search_memories(
drawers_col, dkwargs, query, n_results, wing, room, source_file
)
except Exception as e:
- return {"error": f"Search error: {e}"}
+ return _search_error_result(f"Search error: {e}")
# Gather closet hits (best-per-source) to build a boost lookup.
closet_boost_by_source: dict = {} # source_file -> (rank, closet_dist, preview)
diff --git a/tests/test_closets.py b/tests/test_closets.py
index 4744c1c..ba017b8 100644
--- a/tests/test_closets.py
+++ b/tests/test_closets.py
@@ -1711,7 +1711,12 @@ class TestDrawerGrepExpansion:
)
result = search_memories("JWT authentication", palace_path)
- assert result["results"]
+ # Surface the full envelope when search fails (Windows CI has flaked
+ # with KeyError on a bare ``result["results"]`` after a mid-query
+ # error dict that lacked the key).
+ assert "results" in result, f"search envelope missing results: {result!r}"
+ assert result["results"], f"hybrid search returned no hits: {result!r}"
+ assert "error" not in result, f"hybrid search failed: {result!r}"
boosted = [h for h in result["results"] if h["matched_via"] == "drawer+closet"]
assert boosted, "hybrid search should mark the closet-agreeing source"
top = boosted[0]
diff --git a/tests/test_searcher.py b/tests/test_searcher.py
index c2fe5b9..da8b9b0 100644
--- a/tests/test_searcher.py
+++ b/tests/test_searcher.py
@@ -196,6 +196,9 @@ class TestSearchMemories:
result = search_memories("test", "/fake/path")
assert "error" in result
assert "query failed" in result["error"]
+ # Callers (and CI assertions) index ``results`` unconditionally ā
+ # error envelopes must not omit the key (Windows KeyError flake).
+ assert result["results"] == []
def test_search_memories_vector_path_uses_explicit_collection_name(self):
mock_col = MagicMock()
diff --git a/tests/test_sqlite_exact_backend.py b/tests/test_sqlite_exact_backend.py
index 1acf12d..8bdcdb0 100644
--- a/tests/test_sqlite_exact_backend.py
+++ b/tests/test_sqlite_exact_backend.py
@@ -551,6 +551,49 @@ def test_sqlite_exact_read_only_reopens_when_wal_appears_after_immutable_open(tm
reader_backend.close_palace(palace)
+def test_sqlite_exact_immutable_reader_keeps_cache_on_partial_wal_sidecar(tmp_path):
+ """A lone -wal or -shm file must not retire the immutable reader.
+
+ Incomplete sidecar pairs are a transient mid-open state; forcing a
+ reconnect would raise from ``_connect_read_only`` and break recall.
+ """
+ writer_backend, writer = _collection(tmp_path)
+ palace = PalaceRef(id=str(tmp_path), local_path=str(tmp_path))
+ writer.add(ids=["seed"], documents=["seed"], metadatas=[{}], embeddings=[[1, 0]])
+ with writer._handle.lock:
+ writer._handle.conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
+ writer._handle.conn.commit()
+ writer_backend.close_palace(palace)
+
+ wal_path = tmp_path / "sqlite_exact.sqlite3-wal"
+ shm_path = tmp_path / "sqlite_exact.sqlite3-shm"
+ assert not wal_path.exists() and not shm_path.exists()
+
+ reader_backend = SQLiteExactBackend()
+ first = reader_backend.get_collection(
+ palace=palace,
+ collection_name="mempalace_drawers",
+ create=False,
+ options={"read_only": True},
+ )
+ first_handle = first._handle
+ assert first_handle.immutable is True
+
+ # Simulate a torn writer open: only one sidecar present.
+ wal_path.write_bytes(b"not-a-real-wal")
+ second = reader_backend.get_collection(
+ palace=palace,
+ collection_name="mempalace_drawers",
+ create=False,
+ options={"read_only": True},
+ )
+ assert second._handle is first_handle
+ assert first_handle.closed is False
+ assert second.count() == 1
+
+ reader_backend.close_palace(palace)
+
+
def test_sqlite_exact_direct_write_contends_with_palace_owner(tmp_path, monkeypatch):
from mempalace.palace import MineAlreadyRunning