fix: preflight HNSW divergence before every col.count() call site the audit found

hnsw_capacity_status() (chroma.py) exists precisely to preflight the
#1222 SIGSEGV/pyo3-panic class before anything touches the HNSW
segment, but repo-wide it was wired into only 4 call sites while raw
count()/collection.count() is called at 20+ others -- a bare
except Exception around count() cannot catch a native crash, since
the process dies regardless of any Python try/except. This wires the
existing, already-tested probe into the 7 remaining call sites the
audit identified as CRITICAL:

- #89 palace.py::_enforce_embedder_identity -- the universal
  get_collection() chokepoint every tool passes through, previously
  guarded only by except Exception. Highest leverage: skips this
  bookkeeping-only check on divergence instead of risking count().
- #90 migrate.py::migrate -- routes straight to the same
  SQLite-extraction fallback the except branch already used, instead
  of ever reaching col.count() when diverged.
- #91 repair.py::scan_palace / prune_corrupt -- both abort with the
  existing from-sqlite recovery guidance instead of opening the
  collection.
- #10 repair.py::rebuild_index -- preflights divergence alongside its
  existing sqlite-integrity and poisoned-max-seq-id preflights, before
  opening the collection.
- #13 repair.py::rebuild_index never rebuilt or reported on the
  closets collection -- now warns when closets is still diverged
  after a drawers-only rebuild, pointing at --mode from-sqlite instead
  of letting 'Repair complete' stand unqualified.
- #92 dedup.py::get_source_groups -- takes an optional palace_path
  (threaded from both callers) to preflight before count(); omitted by
  existing tests, which keep their pre-existing behavior.
- #93 miner.py::status -- preflights before the ChromaDB-client
  fallback path (used when the direct sqlite read is unavailable).

7 new regression tests, each confirmed failing against the pre-fix
code (via git stash of the source files only) and passing after the
fix. One existing dedup.py test updated for the new palace_path kwarg
in its call-signature assertion. Full suite: 3154 passed, 1 unrelated
pre-existing flake (test_mcp_server.py peer-writer-lock module-global
state leaking across test files in full-suite ordering -- this diff
never touches mcp_server.py).
This commit is contained in:
KeilerHirsch
2026-07-28 17:18:02 +02:00
parent aa89bd8227
commit 8b5e372951
10 changed files with 324 additions and 19 deletions
+20 -3
View File
@@ -50,12 +50,29 @@ def _get_palace_path():
return os.path.join(os.path.expanduser("~"), ".mempalace", "palace")
def get_source_groups(col, min_count=MIN_DRAWERS_TO_CHECK, source_pattern=None, wing=None):
def get_source_groups(
col, min_count=MIN_DRAWERS_TO_CHECK, source_pattern=None, wing=None, palace_path=None
):
"""Group drawers by source_file, return groups with min_count+ entries.
If wing is specified, only considers drawers in that wing. This catches
cross-wing duplicates when the same source was mined into multiple wings.
``palace_path``, when passed, preflights HNSW divergence before count():
a diverged segment can hit the #1222 SIGSEGV/panic class, which a
try/except around count() cannot catch. Omitted by existing callers
that don't have a palace_path handy (e.g. tests) -- the check is simply
skipped in that case, matching this function's pre-existing behavior.
"""
if palace_path is not None:
from .backends.chroma import hnsw_capacity_status
capacity_info = hnsw_capacity_status(palace_path, COLLECTION_NAME)
if capacity_info.get("diverged"):
print(f"\n HNSW index is diverged: {capacity_info.get('message', '')}")
print(" Run `mempalace repair --mode from-sqlite --archive-existing` first.")
return {}
total = col.count()
groups = defaultdict(list)
@@ -134,7 +151,7 @@ def show_stats(palace_path=None):
palace_path = palace_path or _get_palace_path()
col = get_collection(palace_path, COLLECTION_NAME)
groups = get_source_groups(col)
groups = get_source_groups(col, palace_path=palace_path)
total_drawers = sum(len(ids) for ids in groups.values())
print(f"\n Sources with {MIN_DRAWERS_TO_CHECK}+ drawers: {len(groups)}")
@@ -174,7 +191,7 @@ def dedup_palace(
if wing:
print(f" Wing: {wing}")
groups = get_source_groups(col, min_count, source_pattern, wing=wing)
groups = get_source_groups(col, min_count, source_pattern, wing=wing, palace_path=palace_path)
print(f"\n Sources to check: {len(groups)}")
t0 = time.time()
+34 -13
View File
@@ -244,22 +244,43 @@ def migrate(palace_path: str, dry_run: bool = False, confirm: bool = False):
# A plain count() is not enough: some 0.6.x -> 1.5.x migrated collections
# are readable but silently drop upsert/delete operations. In that state,
# migrate must rebuild from SQLite instead of returning "No migration needed."
#
# Preflight HNSW divergence before touching the collection at all: the
# #1222 SIGSEGV/panic class crashes on count() against a diverged
# segment, and a native crash can't be caught by the except Exception
# below -- a diverged palace must never reach col.count() in the first
# place. The already-diverged case degrades to exactly the same
# SQLite-extraction path the except branch below already falls back to.
from .backends.chroma import hnsw_capacity_status
try:
col = ChromaBackend().get_collection(palace_path, "mempalace_drawers")
count = col.count()
if collection_write_roundtrip_works(col):
print(f"\n Palace is already readable and writable by chromadb {target_version}.")
print(f" {count} drawers found. No migration needed.")
return True
print(
f"\n Palace is readable by chromadb {target_version}, but write/delete verification failed."
)
print(" Rebuilding from SQLite to restore native write/delete behavior...")
capacity_info = hnsw_capacity_status(palace_path, "mempalace_drawers")
except Exception:
print(f"\n Palace is NOT readable by chromadb {target_version}.")
capacity_info = {}
if capacity_info.get("diverged"):
print(
f"\n Palace is NOT readable by chromadb {target_version}: HNSW index diverged from SQLite."
)
print(f" ({capacity_info.get('message', 'divergence detected')})")
print(" Extracting from SQLite directly...")
else:
try:
col = ChromaBackend().get_collection(palace_path, "mempalace_drawers")
count = col.count()
if collection_write_roundtrip_works(col):
print(f"\n Palace is already readable and writable by chromadb {target_version}.")
print(f" {count} drawers found. No migration needed.")
return True
print(
f"\n Palace is readable by chromadb {target_version}, but write/delete verification failed."
)
print(" Rebuilding from SQLite to restore native write/delete behavior...")
except Exception:
print(f"\n Palace is NOT readable by chromadb {target_version}.")
print(" Extracting from SQLite directly...")
# Extract all drawers via raw SQL
drawers = extract_drawers_from_sqlite(db_path)
+12 -1
View File
@@ -2138,7 +2138,7 @@ def status(palace_path: str):
un-bootstrapped collection, or an unexpected schema); the fallback also
emits the state-specific guidance for absent/empty palaces.
"""
from .backends.chroma import _sqlite_wing_room_counts
from .backends.chroma import _sqlite_wing_room_counts, hnsw_capacity_status
counts = _sqlite_wing_room_counts(palace_path, "mempalace_drawers")
if counts is not None:
@@ -2150,6 +2150,17 @@ def status(palace_path: str):
if col is None:
return
# Preflight HNSW divergence before falling back to the ChromaDB client
# path: count() on a diverged segment can hit the #1222 SIGSEGV/panic
# class, which a try/except around count() cannot catch. This fallback
# only runs when the direct sqlite read above was unavailable, so it's
# the one place in this function that still touches count() directly.
capacity_info = hnsw_capacity_status(palace_path, "mempalace_drawers")
if capacity_info.get("diverged"):
print(f"\n HNSW index is diverged: {capacity_info.get('message', '')}")
print(" Run `mempalace repair --mode from-sqlite --archive-existing` first.")
return
# Count by wing and room — paginate to avoid SQLite "too many SQL
# variables" error on large palaces (see #802, #850).
total = col.count()
+20 -1
View File
@@ -138,10 +138,29 @@ def _enforce_embedder_identity(collection, palace_path, collection_name, *, crea
return
if state == "unknown" and stored is None:
# Preflight HNSW divergence before touching count(): this is the
# universal chokepoint every tool passes through via
# get_collection(), and count() on a diverged segment can raise
# chromadb's rust-level pyo3_runtime.PanicException or hard-segfault
# (#1222) -- neither of which the except Exception below can catch,
# since a native crash takes the whole process down regardless of
# any Python try/except. A diverged palace must never reach count()
# here; this bookkeeping-only identity check simply skips itself
# (count treated as unknown, matching the except-Exception fallback
# already below) rather than risk the read.
try:
count = collection.count()
from .backends.chroma import hnsw_capacity_status
diverged = hnsw_capacity_status(str(palace_path), str(collection_name)).get("diverged")
except Exception:
diverged = False
if diverged:
count = None
else:
try:
count = collection.count()
except Exception:
count = None
if count == 0:
if create:
try:
+50
View File
@@ -331,6 +331,17 @@ def scan_palace(palace_path=None, only_wing=None, collection_name: Optional[str]
print(f"\n Palace: {palace_path}")
print(" Loading...")
# Preflight HNSW divergence before opening the collection: count() on a
# diverged segment can hit the #1222 SIGSEGV/panic class, which a
# try/except around count() cannot catch (a native crash takes the
# whole process down). scan_palace is meant to find corruption, not
# crash on the exact corruption class it should be reporting.
capacity_info = hnsw_capacity_status(palace_path, collection_name)
if capacity_info.get("diverged"):
print(f"\n HNSW index is diverged: {capacity_info.get('message', '')}")
print(index_read_recovery_guidance())
return set(), set()
col = ChromaBackend().get_collection(palace_path, collection_name)
where = {"wing": only_wing} if only_wing else None
@@ -416,6 +427,15 @@ def prune_corrupt(palace_path=None, confirm=False, collection_name: Optional[str
print(" Re-run with --confirm to actually delete.")
return
# Preflight HNSW divergence before opening the collection — see
# scan_palace's identical guard for why this can't rely on except
# Exception around count() alone.
capacity_info = hnsw_capacity_status(palace_path, collection_name)
if capacity_info.get("diverged"):
print(f"\n HNSW index is diverged: {capacity_info.get('message', '')}")
print(index_read_recovery_guidance())
return
col = ChromaBackend().get_collection(palace_path, collection_name)
before = col.count()
print(f" Collection size before: {before:,}")
@@ -1018,6 +1038,19 @@ def rebuild_index(
if preflight is not None:
return
# Preflight HNSW divergence before opening the collection: status()
# already has this same guard via hnsw_capacity_status (docstring above
# this module's status() references it as "the safe pattern"), but
# rebuild_index -- the legacy rebuild the CLI's rebuild-index subcommand
# dispatches straight to -- opens the collection and calls col.count()
# directly, wrapped only in except Exception, which cannot catch the
# #1222 SIGSEGV/panic class a diverged segment triggers.
capacity_info = hnsw_capacity_status(palace_path, collection_name)
if capacity_info.get("diverged"):
progress(f"\n HNSW index is diverged: {capacity_info.get('message', '')}")
progress(index_read_recovery_guidance())
return
backend = ChromaBackend()
try:
col = backend.get_collection(palace_path, collection_name)
@@ -1098,6 +1131,23 @@ def rebuild_index(
print(f"\n Repair complete. {filed} drawers rebuilt.")
print(" HNSW index is now clean with cosine distance metric.")
# rebuild_index only ever touches collection_name (drawers by default).
# status() checks divergence for BOTH drawers and closets and recommends
# --mode from-sqlite (which rebuilds both via _recoverable_collections()),
# but a caller who ran this legacy rebuild instead would otherwise see
# an unqualified "Repair complete" even when closets remains diverged
# and just as capable of crashing reads via the same #1222 mechanism (#13).
if collection_name == _drawers_collection_name():
closets_info = hnsw_capacity_status(palace_path, CLOSETS_COLLECTION_NAME)
if closets_info.get("diverged"):
print(
f"\n NOTE: the closets index is still diverged "
f"({closets_info.get('message', '')}).\n"
" This rebuild only covers drawers. Run "
"`mempalace repair --mode from-sqlite --archive-existing`\n"
" to rebuild closets too."
)
print(f"\n{'=' * 55}\n")
+19 -1
View File
@@ -9,6 +9,22 @@ from mempalace import dedup
# ── get_source_groups ─────────────────────────────────────────────────
def test_get_source_groups_aborts_on_hnsw_divergence():
"""count() on a diverged HNSW segment can hard-crash the process
(#1222); get_source_groups must not call it when hnsw_capacity_status
reports divergence for the caller-supplied palace_path (#92). Omitting
palace_path (as every existing test above does) skips the check
entirely -- this only fires when a real caller passes one."""
col = MagicMock()
with patch(
"mempalace.backends.chroma.hnsw_capacity_status",
return_value={"diverged": True, "message": "test divergence"},
):
groups = dedup.get_source_groups(col, palace_path="/fake/palace")
assert groups == {}
col.count.assert_not_called()
def test_get_source_groups_basic():
col = MagicMock()
col.count.return_value = 5
@@ -253,7 +269,9 @@ def test_dedup_palace_with_wing(mock_get_collection, mock_groups, mock_dedup_gro
mock_groups.return_value = {}
dedup.dedup_palace(palace_path=str(tmp_path), wing="test_wing", dry_run=True)
mock_groups.assert_called_once_with(mock_col, 5, None, wing="test_wing")
mock_groups.assert_called_once_with(
mock_col, 5, None, wing="test_wing", palace_path=str(tmp_path)
)
@patch("mempalace.dedup.dedup_source_group")
+26
View File
@@ -10,6 +10,7 @@ only the configured model name (cheap), and persistence is exercised with
import os
import warnings
from unittest.mock import MagicMock, patch
import pytest
@@ -28,6 +29,31 @@ from mempalace.backends.base import (
# ---------------------------------------------------------------------------
def test_enforce_embedder_identity_skips_count_on_hnsw_divergence():
"""count() on a diverged HNSW segment can hard-crash the process
(#1222) -- a try/except cannot save it, since a native crash takes the
whole process down regardless. _enforce_embedder_identity runs on
EVERY get_collection() call (the universal chokepoint every tool
passes through) and must never reach count() when hnsw_capacity_status
reports divergence (#89)."""
from mempalace.palace import _enforce_embedder_identity
collection = MagicMock()
collection.effective_embedder_identity.side_effect = Exception("not supported")
collection.get_stored_embedder_identity.return_value = None
with (
patch("mempalace.embedding.current_model_name", return_value="minilm"),
patch(
"mempalace.backends.chroma.hnsw_capacity_status",
return_value={"diverged": True, "message": "test divergence"},
),
):
_enforce_embedder_identity(collection, "/fake/palace", "mempalace_drawers", create=True)
collection.count.assert_not_called()
def test_unknown_when_nothing_stored():
assert check_embedder_identity(None, EmbedderIdentity("minilm", 384)) == "unknown"
+27
View File
@@ -198,6 +198,33 @@ def test_extract_drawers_returns_drawers(tmp_path):
assert drawers[0]["metadata"] == {"wing": "personal", "room": "2026-04-26"}
def test_migrate_skips_count_on_hnsw_divergence(tmp_path, capsys):
"""count() on a diverged HNSW segment can hard-crash the process
(#1222); migrate() must route straight to the SQLite-extraction
fallback -- the same path the except Exception branch already falls
back to -- instead of ever calling col.count() when
hnsw_capacity_status reports divergence (#90)."""
palace_dir = tmp_path / "palace"
palace_dir.mkdir()
(palace_dir / "chroma.sqlite3").write_text("db")
with (
patch("mempalace.migrate.detect_chromadb_version", return_value="1.x"),
patch("mempalace.backends.chroma.ChromaBackend") as mock_backend,
patch(
"mempalace.backends.chroma.hnsw_capacity_status",
return_value={"diverged": True, "message": "test divergence"},
),
patch("mempalace.migrate.extract_drawers_from_sqlite", return_value=[]),
):
mock_backend.backend_version.return_value = "1.5.8"
migrate(str(palace_dir), dry_run=True)
mock_backend.return_value.get_collection.assert_not_called()
out = capsys.readouterr().out
assert "HNSW index diverged" in out
def test_migrate_dry_run_rebuilds_when_collection_is_readable_but_not_writable(tmp_path, capsys):
palace_dir = tmp_path / "palace"
palace_dir.mkdir()
+25
View File
@@ -1020,6 +1020,31 @@ def test_status_palace_dir_without_db_reports_uninitialized(tmp_path, capsys):
assert list(palace_path.iterdir()) == []
def test_status_aborts_on_hnsw_divergence(tmp_path, capsys):
"""count() on a diverged HNSW segment can hard-crash the process
(#1222); status()'s ChromaDB-client fallback (used when the direct
sqlite read is unavailable) must preflight divergence before ever
calling count(), not just wrap it in except Exception (#93)."""
from unittest.mock import patch
class FakeCol:
def count(self):
raise AssertionError("count() must not be called when diverged")
with (
patch("mempalace.miner._open_collection_or_explain", return_value=FakeCol()),
patch(
"mempalace.backends.chroma.hnsw_capacity_status",
return_value={"diverged": True, "message": "test divergence"},
),
):
status(str(tmp_path))
out = capsys.readouterr().out
assert "HNSW index is diverged" in out
assert "MemPalace Status" not in out
def test_status_handles_none_metadata_without_crash(tmp_path, capsys):
"""status must not crash when col.get returns a None entry in metadatas.
+91
View File
@@ -177,6 +177,20 @@ def _install_mock_backend(mock_backend_cls, collection):
return mock_backend
@patch("mempalace.repair.hnsw_capacity_status")
@patch("mempalace.repair.ChromaBackend")
def test_scan_palace_aborts_on_hnsw_divergence(mock_backend_cls, mock_capacity, tmp_path):
"""count() on a diverged HNSW segment can hard-crash the process
(#1222) -- a try/except cannot save it. scan_palace must never reach
ChromaBackend().get_collection()/count() when hnsw_capacity_status
reports divergence (#91)."""
mock_capacity.return_value = {"diverged": True, "message": "test divergence"}
good, bad = repair.scan_palace(palace_path=str(tmp_path))
assert good == set()
assert bad == set()
mock_backend_cls.assert_not_called()
@patch("mempalace.repair.ChromaBackend")
def test_scan_palace_no_ids(mock_backend_cls, tmp_path):
mock_col = MagicMock()
@@ -250,6 +264,18 @@ def test_scan_palace_with_wing_filter(mock_backend_cls, tmp_path):
# ── prune_corrupt ─────────────────────────────────────────────────────
@patch("mempalace.repair.hnsw_capacity_status")
@patch("mempalace.repair.ChromaBackend")
def test_prune_corrupt_aborts_on_hnsw_divergence(mock_backend_cls, mock_capacity, tmp_path):
"""Same guard as scan_palace: a failed purge attempt against a
diverged segment must never reach count()/delete() (#91)."""
bad_file = tmp_path / "corrupt_ids.txt"
bad_file.write_text("bad1\n")
mock_capacity.return_value = {"diverged": True, "message": "test divergence"}
repair.prune_corrupt(palace_path=str(tmp_path), confirm=True)
mock_backend_cls.assert_not_called()
@patch("mempalace.repair.ChromaBackend")
def test_prune_corrupt_no_file(mock_backend_cls, tmp_path):
# Should print message and return without error
@@ -387,6 +413,71 @@ def test_rebuild_index_success(mock_backend_cls, mock_copy, tmp_path):
mock_new_col.add.assert_not_called()
@patch("mempalace.repair.hnsw_capacity_status")
@patch("mempalace.repair.ChromaBackend")
def test_rebuild_index_aborts_on_hnsw_divergence_preflight(
mock_backend_cls, mock_capacity, tmp_path
):
"""count() on a diverged HNSW segment can hard-crash the process
(#1222); rebuild_index's legacy path -- the one the CLI's rebuild-index
subcommand dispatches straight to -- must preflight divergence before
ever opening the collection, not just wrap count() in except Exception
(#10)."""
sqlite_path = tmp_path / "chroma.sqlite3"
with sqlite3.connect(sqlite_path) as conn:
conn.execute("CREATE TABLE dummy(id INTEGER PRIMARY KEY)")
conn.commit()
mock_capacity.return_value = {"diverged": True, "message": "test divergence"}
msgs: list[str] = []
repair.rebuild_index(palace_path=str(tmp_path), progress=msgs.append)
mock_backend_cls.assert_not_called()
assert "diverged" in "\n".join(msgs).lower()
@patch("mempalace.repair._copy_file_no_follow")
@patch("mempalace.repair.hnsw_capacity_status")
@patch("mempalace.repair.ChromaBackend")
def test_rebuild_index_warns_when_closets_still_diverged(
mock_backend_cls, mock_capacity, mock_copy, tmp_path, capsys
):
"""rebuild_index only ever rebuilds the drawers collection passed to
it; if closets is still diverged afterward, the printed summary must
say so instead of an unqualified 'Repair complete', since closets is
just as capable of crashing reads via the same #1222 mechanism (#13)."""
sqlite_path = tmp_path / "chroma.sqlite3"
with sqlite3.connect(sqlite_path) as conn:
conn.execute("CREATE TABLE dummy(id INTEGER PRIMARY KEY)")
conn.commit()
mock_col = MagicMock()
mock_col.count.return_value = 2
mock_col.get.return_value = {
"ids": ["id1", "id2"],
"documents": ["doc1", "doc2"],
"metadatas": [{"wing": "a"}, {"wing": "b"}],
}
mock_new_col = MagicMock()
mock_new_col.count.return_value = 2
mock_temp_col = MagicMock()
mock_temp_col.count.return_value = 2
mock_backend = _install_mock_backend(mock_backend_cls, mock_col)
mock_backend.create_collection.side_effect = [mock_temp_col, mock_new_col]
# First call: drawers preflight (not diverged, rebuild proceeds).
# Second call: post-rebuild closets check (still diverged).
mock_capacity.side_effect = [
{"diverged": False, "message": ""},
{"diverged": True, "message": "closets still diverged"},
]
repair.rebuild_index(palace_path=str(tmp_path))
out = capsys.readouterr().out
assert "Repair complete" in out
assert "closets" in out.lower()
assert "closets still diverged" in out
@patch("mempalace.repair._copy_file_no_follow")
@patch("mempalace.repair.ChromaBackend")
def test_rebuild_index_ignores_missing_temp_collection_at_start(