From cd7a8658a221eb04ff6624194faead67cdbe6e49 Mon Sep 17 00:00:00 2001 From: Pim Messelink Date: Mon, 29 Jun 2026 05:01:59 +0800 Subject: [PATCH] fix(backends): require SQLite magic header for chroma + sqlite_exact detect() (#1893) (#1896) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(chroma): require SQLite magic header for ChromaBackend.detect() (#1893) Closes #1893. ChromaBackend.detect() was returning True for a 0-byte chroma.sqlite3 file because the check was just os.path.isfile(...). On a palace that has any other backend marker alongside a stale 0-byte chroma.sqlite3, resolve_backend_name then raises BackendMismatchError and the palace becomes unopenable until the user manually rm's the empty file. The 0-byte file appears as a side effect of any sqlite3.connect() on a missing path — Python creates the file immediately but writes the SQLite header only on the first statement. So any code path that touches the chroma.sqlite3 path with bare sqlite3.connect(), including chromadb's own PersistentClient lazy-init (see the comment at backends/chroma.py:2052), can leave a 0-byte artifact behind. Fix: detect() now reads the first 16 bytes and compares to the SQLite magic prefix b"SQLite format 3\x00" instead of relying on file presence alone. One extra open() + 16-byte read; detect() isn't a hot path. Properties: - Rejects 0-byte files (the symptom #1893 is about). - Rejects non-SQLite garbage at the canonical path (partial writes, etc.). - Doesn't false-negative on real chroma palaces: any chroma palace whose PersistentClient has done any work has the magic header on disk (verified — CREATE TABLE is enough to land the header). - Doesn't couple detect() to chroma's specific schema; the magic header is stable across chromadb releases. Test sweep: many test files used (chroma.sqlite3).touch() or .write_bytes(b"") as a "fake palace" shortcut, exploiting the loose isfile() check (one such site even had the comment "# pass the isfile guard"). After this change, those stand-ins no longer register as chroma palaces. Introduced tests/_chroma_palace_helper.py::make_minimal_chroma_sqlite following the existing _backend_conformance.py precedent, and updated 15 call sites across 8 test files to use it. The existing test_chroma_detect_matches_palace_with_chroma_sqlite (which encoded the buggy semantics with write_bytes(b"")) is renamed to test_chroma_detect_matches_palace_with_sqlite_header and now writes a real SQLite database via the helper. Added two new tests for the rejection paths (empty file, non-SQLite garbage). Full env-cleared suite: 3137 passed, 20 skipped, 0 failed. ruff check and ruff format --check both clean. Co-Authored-By: Claude Opus 4.7 Claude-Session: https://claude.ai/code/session_01KC5Qsknh2zFRtRvVyjXiTA * fix(sqlite_exact): require SQLite magic header for SQLiteExactBackend.detect() Per gemini-code-assist review on #1892 PR #1896: SQLiteExactBackend has the same os.path.isfile() detection pattern as ChromaBackend did, with the same 0-byte-file vulnerability. Mirrors the chroma fix for repo-wide consistency. - SQLiteExactBackend.detect() now does the same 16-byte SQLite magic-prefix check as ChromaBackend.detect(). - _chroma_palace_helper.py: factored its body into a private _write_minimal_sqlite_file() and gained a sibling make_minimal_sqlite_exact_sqlite() for the sqlite_exact filename. No churn to any existing chroma call sites. - test_sqlite_exact_backend.py:426 (the one site that wrote b"" for sqlite_exact.sqlite3) updated to use the new helper. - Three new tests in test_sqlite_exact_backend.py mirror the chroma trio: matches with valid header, rejects empty file, rejects non-SQLite garbage. Full env-cleared suite: 3140 passed, 20 skipped, 0 failed. Co-Authored-By: Claude Opus 4.7 Claude-Session: https://claude.ai/code/session_01KC5Qsknh2zFRtRvVyjXiTA --------- Co-authored-by: Claude Opus 4.7 --- mempalace/backends/chroma.py | 21 ++++++++++- mempalace/backends/sqlite_exact.py | 18 +++++++++- tests/_chroma_palace_helper.py | 57 ++++++++++++++++++++++++++++++ tests/test_backends.py | 36 +++++++++++++++++-- tests/test_daemon.py | 4 ++- tests/test_mcp_server.py | 4 ++- tests/test_palace.py | 10 +++--- tests/test_qdrant_backend.py | 3 +- tests/test_repair.py | 8 +++-- tests/test_searcher.py | 4 ++- tests/test_sqlite_exact_backend.py | 40 +++++++++++++++++++-- tests/test_sync.py | 6 ++-- 12 files changed, 191 insertions(+), 20 deletions(-) create mode 100644 tests/_chroma_palace_helper.py diff --git a/mempalace/backends/chroma.py b/mempalace/backends/chroma.py index 4b83233..cc12a93 100644 --- a/mempalace/backends/chroma.py +++ b/mempalace/backends/chroma.py @@ -2228,7 +2228,26 @@ class ChromaBackend(BaseBackend): @classmethod def detect(cls, path: str) -> bool: - return os.path.isfile(os.path.join(path, "chroma.sqlite3")) + """Return True when ``path`` looks like a chroma palace. + + Verifies the SQLite magic header rather than file presence alone. + Bare ``sqlite3.connect()`` against a missing path leaves a 0-byte + file behind (the SQLite header is written on the first statement, + not on connection), so file-presence alone treats those artifacts + as real chroma palaces and breaks multi-backend resolution. The + 16-byte ``SQLite format 3\\x00`` magic prefix is written as soon + as chromadb's ``PersistentClient`` does any work, so this check + accepts every real chroma palace while rejecting empty / garbage + files. See #1893. + """ + db_path = os.path.join(path, "chroma.sqlite3") + if not os.path.isfile(db_path): + return False + try: + with open(db_path, "rb") as f: + return f.read(16) == b"SQLite format 3\x00" + except OSError: + return False # ------------------------------------------------------------------ # Legacy (pre-RFC 001) surface — retained while callers migrate. diff --git a/mempalace/backends/sqlite_exact.py b/mempalace/backends/sqlite_exact.py index 53f1cde..fd29dfa 100644 --- a/mempalace/backends/sqlite_exact.py +++ b/mempalace/backends/sqlite_exact.py @@ -1045,7 +1045,23 @@ class SQLiteExactBackend(BaseBackend): @classmethod def detect(cls, path: str) -> bool: - return os.path.isfile(os.path.join(path, _DB_FILENAME)) + """Return True when ``path`` looks like a sqlite_exact palace. + + Verifies the SQLite magic header rather than file presence alone, for + the same reason as :py:meth:`mempalace.backends.chroma.ChromaBackend.detect`: + bare ``sqlite3.connect()`` against a missing path leaves a 0-byte file + behind because the SQLite header is written on the first statement, + not on connection. The 16-byte ``SQLite format 3\\x00`` magic prefix + accepts every real palace while rejecting empty / garbage files. See #1893. + """ + db_path = os.path.join(path, _DB_FILENAME) + if not os.path.isfile(db_path): + return False + try: + with open(db_path, "rb") as f: + return f.read(16) == b"SQLite format 3\x00" + except OSError: + return False def create_collection(self, palace_path: str, collection_name: str) -> SQLiteExactCollection: return self.get_collection(palace_path, collection_name, create=True) diff --git a/tests/_chroma_palace_helper.py b/tests/_chroma_palace_helper.py new file mode 100644 index 0000000..b55806e --- /dev/null +++ b/tests/_chroma_palace_helper.py @@ -0,0 +1,57 @@ +"""Shared helpers: create minimal valid palace-marker SQLite files for tests. + +Many tests want to stand up "a chroma / sqlite_exact palace" cheaply — +historically they did this with ``(path / ".sqlite3").touch()`` or +``write_bytes(b"")``, relying on the backend ``detect()`` methods' old +``os.path.isfile()`` semantics. Post-#1893, both ``ChromaBackend.detect()`` +and ``SQLiteExactBackend.detect()`` require a valid SQLite magic header, so +the empty stand-in no longer registers. These helpers create the minimum +required to make detection fire without standing up a full palace. + +This module is intentionally not a ``test_*`` file: it ships utilities, not +tests. +""" + +import sqlite3 +from pathlib import Path +from typing import Union + + +def _write_minimal_sqlite_file(db_path: Path) -> None: + """Write a valid SQLite magic header at ``db_path``. + + Writing any statement is sufficient to land the 16-byte + ``SQLite format 3\\x00`` magic prefix that the backend ``detect()`` + methods check. + """ + + conn = sqlite3.connect(db_path) + try: + conn.execute("CREATE TABLE _detect_smoke(x)") + conn.commit() + finally: + conn.close() + + +def make_minimal_chroma_sqlite(palace_path: Union[Path, str]) -> Path: + """Create ``/chroma.sqlite3`` with a valid SQLite header. + + Returns the path to the file. Backs + :py:meth:`mempalace.backends.chroma.ChromaBackend.detect`. + """ + + db_path = Path(palace_path) / "chroma.sqlite3" + _write_minimal_sqlite_file(db_path) + return db_path + + +def make_minimal_sqlite_exact_sqlite(palace_path: Union[Path, str]) -> Path: + """Create ``/sqlite_exact.sqlite3`` with a valid SQLite header. + + Returns the path to the file. Backs + :py:meth:`mempalace.backends.sqlite_exact.SQLiteExactBackend.detect`. + """ + + db_path = Path(palace_path) / "sqlite_exact.sqlite3" + _write_minimal_sqlite_file(db_path) + return db_path diff --git a/tests/test_backends.py b/tests/test_backends.py index 5d437c2..3168ec7 100644 --- a/tests/test_backends.py +++ b/tests/test_backends.py @@ -178,12 +178,44 @@ def test_resolve_backend_priority_order(tmp_path): assert resolve_backend_for_palace() == "chroma" -def test_chroma_detect_matches_palace_with_chroma_sqlite(tmp_path): - (tmp_path / "chroma.sqlite3").write_bytes(b"") +def test_chroma_detect_matches_palace_with_sqlite_header(tmp_path): + """A real SQLite database at ``/chroma.sqlite3`` registers as chroma. + + Uses ``sqlite3.connect`` + a write so the SQLite magic header is actually + on disk — the only thing detection looks at. + """ + db_path = tmp_path / "chroma.sqlite3" + conn = sqlite3.connect(db_path) + conn.execute("CREATE TABLE detect_smoke(x)") + conn.commit() + conn.close() assert ChromaBackend.detect(str(tmp_path)) is True assert ChromaBackend.detect(str(tmp_path.parent)) is False +def test_chroma_detect_rejects_empty_chroma_sqlite(tmp_path): + """A 0-byte ``chroma.sqlite3`` is not a chroma palace (closes #1893). + + Bare ``sqlite3.connect()`` against a missing path leaves a 0-byte file + behind because the SQLite header is written on the first statement, not + on connect. Detection must reject that artifact so it cannot trip + ``BackendMismatchError`` against a real non-chroma backend marker in the + same directory. + """ + (tmp_path / "chroma.sqlite3").write_bytes(b"") + assert ChromaBackend.detect(str(tmp_path)) is False + + +def test_chroma_detect_rejects_non_sqlite_file(tmp_path): + """A non-SQLite file at the ``chroma.sqlite3`` path is not chroma. + + Defends against partial writes / garbage content / anything that lands at + the canonical path but isn't actually a SQLite database. + """ + (tmp_path / "chroma.sqlite3").write_bytes(b"not a sqlite file" * 4) + assert ChromaBackend.detect(str(tmp_path)) is False + + def test_chroma_lexical_search_uses_sqlite_fts_not_full_collection_scan(tmp_path): db_path = tmp_path / "chroma.sqlite3" conn = sqlite3.connect(db_path) diff --git a/tests/test_daemon.py b/tests/test_daemon.py index d8d1127..bf5ede3 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -5,6 +5,8 @@ import time import pytest +from _chroma_palace_helper import make_minimal_chroma_sqlite + from mempalace import daemon from mempalace import service @@ -728,7 +730,7 @@ def test_run_sync_structured_errors_on_sync_failures(tmp_path, monkeypatch): palace = tmp_path / "palace" palace.mkdir() - (palace / "chroma.sqlite3").touch() + make_minimal_chroma_sqlite(palace) def _raise(exc): def fn(**kw): diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 89bd651..18462eb 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -16,6 +16,8 @@ from unittest.mock import MagicMock import pytest +from _chroma_palace_helper import make_minimal_chroma_sqlite + # ── MCP entry point: PYTHONPATH stripping ──────────────────────────────── @@ -210,7 +212,7 @@ class TestColdStartDiagnostics: """ palace = tmp_path / "palace" palace.mkdir() - (palace / "chroma.sqlite3").touch() + make_minimal_chroma_sqlite(palace) return str(palace) @staticmethod diff --git a/tests/test_palace.py b/tests/test_palace.py index acd1b49..426924a 100644 --- a/tests/test_palace.py +++ b/tests/test_palace.py @@ -2,6 +2,8 @@ import chromadb +from _chroma_palace_helper import make_minimal_chroma_sqlite + from mempalace.backends import CollectionNotInitializedError, PalaceNotFoundError from mempalace.palace import _open_collection_or_explain, get_collection @@ -94,7 +96,7 @@ def test_open_collection_or_explain_state_e_unexpected_error(tmp_path, monkeypat emit, lines = _capture() palace = tmp_path / "palace" palace.mkdir() - (palace / "chroma.sqlite3").touch() # pass the isfile guard + make_minimal_chroma_sqlite(palace) # pass the isfile guard def boom(*args, **kwargs): raise RuntimeError("disk on fire") @@ -125,7 +127,7 @@ def test_open_collection_or_explain_propagates_palace_not_found_from_backend(tmp emit, lines = _capture() palace = tmp_path / "palace" palace.mkdir() - (palace / "chroma.sqlite3").touch() + make_minimal_chroma_sqlite(palace) def raise_pnf(*args, **kwargs): raise PalaceNotFoundError(str(palace)) @@ -151,7 +153,7 @@ def test_open_collection_or_explain_reraises_backend_closed_error(tmp_path, monk palace = tmp_path / "palace" palace.mkdir() - (palace / "chroma.sqlite3").touch() + make_minimal_chroma_sqlite(palace) def raise_closed(*args, **kwargs): raise BackendClosedError("ChromaBackend has been closed") @@ -171,7 +173,7 @@ def test_open_collection_or_explain_distinguishes_collection_subclass(tmp_path, emit, lines = _capture() palace = tmp_path / "palace" palace.mkdir() - (palace / "chroma.sqlite3").touch() + make_minimal_chroma_sqlite(palace) def raise_cnie(*args, **kwargs): raise CollectionNotInitializedError(str(palace)) diff --git a/tests/test_qdrant_backend.py b/tests/test_qdrant_backend.py index 07e2113..dbb00d4 100644 --- a/tests/test_qdrant_backend.py +++ b/tests/test_qdrant_backend.py @@ -5,6 +5,7 @@ import numpy as np import pytest from _backend_conformance import assert_partition_isolation +from _chroma_palace_helper import make_minimal_chroma_sqlite from mempalace.backends import ( BackendError, @@ -362,7 +363,7 @@ def test_qdrant_marker_participates_in_backend_mismatch(tmp_path, monkeypatch, f backend, col = _collection(tmp_path) col.upsert(ids=["a"], documents=["one"], metadatas=[{}], embeddings=[[1, 0]]) backend.close() - (tmp_path / "chroma.sqlite3").write_bytes(b"") + make_minimal_chroma_sqlite(tmp_path) monkeypatch.setenv("MEMPALACE_BACKEND_EXPLICIT", "chroma") with pytest.raises(BackendMismatchError): diff --git a/tests/test_repair.py b/tests/test_repair.py index 4dec463..ff1d65f 100644 --- a/tests/test_repair.py +++ b/tests/test_repair.py @@ -7,6 +7,8 @@ from unittest.mock import MagicMock, call, patch import pytest +from _chroma_palace_helper import make_minimal_chroma_sqlite + from mempalace import repair @@ -583,7 +585,7 @@ def test_status_returns_empty_when_db_present_no_drawers(tmp_path, capsys): 'uninitialized' (#1498). Mocks sqlite_drawer_count to assert the return-shape contract; see the real-disk sibling below for the no-chromadb-client invariant.""" - (tmp_path / "chroma.sqlite3").touch() + make_minimal_chroma_sqlite(tmp_path) with patch("mempalace.repair.sqlite_drawer_count", return_value=0): result = repair.status(palace_path=str(tmp_path)) @@ -622,7 +624,7 @@ def test_status_falls_through_to_capacity_when_sqlite_count_unreadable(tmp_path) """When sqlite_drawer_count returns None (schema drift / locked file), repair.status must fall through to hnsw_capacity_status instead of short-circuiting on 'empty' (#1498).""" - (tmp_path / "chroma.sqlite3").touch() + make_minimal_chroma_sqlite(tmp_path) with ( patch("mempalace.repair.sqlite_drawer_count", return_value=None), patch("mempalace.repair.hnsw_capacity_status") as capacity_status, @@ -658,7 +660,7 @@ def test_status_default_uses_configured_drawer_collection(tmp_path): # Provide the on-disk preconditions the stratified state helper (#1498) # checks before reaching the capacity probe: chroma.sqlite3 file exists # and sqlite_drawer_count returns a positive number (palace not empty). - (tmp_path / "chroma.sqlite3").touch() + make_minimal_chroma_sqlite(tmp_path) with ( patch("mempalace.repair._drawers_collection_name", return_value="custom_drawers"), patch("mempalace.repair.sqlite_drawer_count", return_value=1), diff --git a/tests/test_searcher.py b/tests/test_searcher.py index c99ae65..bd24638 100644 --- a/tests/test_searcher.py +++ b/tests/test_searcher.py @@ -9,6 +9,8 @@ from unittest.mock import MagicMock, patch import pytest +from _chroma_palace_helper import make_minimal_chroma_sqlite + from mempalace.searcher import SearchError, build_where_filter, search, search_memories @@ -349,7 +351,7 @@ def fake_palace_path(tmp_path): backend instead of raising on State A / State B.""" p = tmp_path / "palace" p.mkdir() - (p / "chroma.sqlite3").touch() + make_minimal_chroma_sqlite(p) return str(p) diff --git a/tests/test_sqlite_exact_backend.py b/tests/test_sqlite_exact_backend.py index 7969305..f6836d4 100644 --- a/tests/test_sqlite_exact_backend.py +++ b/tests/test_sqlite_exact_backend.py @@ -4,6 +4,8 @@ import threading import pytest +from _chroma_palace_helper import make_minimal_chroma_sqlite, make_minimal_sqlite_exact_sqlite + import mempalace.backends.sqlite_exact as sqlite_exact_module from mempalace.backends import ( BackendMismatchError, @@ -410,7 +412,7 @@ def test_palace_wrapper_embeds_for_sqlite_exact(tmp_path, monkeypatch): def test_backend_mismatch_protection(tmp_path, monkeypatch): from mempalace.palace import get_collection - (tmp_path / "chroma.sqlite3").write_bytes(b"") + make_minimal_chroma_sqlite(tmp_path) monkeypatch.setenv("MEMPALACE_BACKEND_EXPLICIT", "sqlite_exact") with pytest.raises(BackendMismatchError): @@ -420,14 +422,46 @@ def test_backend_mismatch_protection(tmp_path, monkeypatch): def test_mixed_backend_artifacts_are_rejected_even_when_chroma_selected(tmp_path, monkeypatch): from mempalace.palace import resolve_backend_name - (tmp_path / "chroma.sqlite3").write_bytes(b"") - (tmp_path / "sqlite_exact.sqlite3").write_bytes(b"") + make_minimal_chroma_sqlite(tmp_path) + make_minimal_sqlite_exact_sqlite(tmp_path) monkeypatch.setenv("MEMPALACE_BACKEND_EXPLICIT", "chroma") with pytest.raises(BackendMismatchError): resolve_backend_name(str(tmp_path)) +def test_sqlite_exact_detect_matches_palace_with_sqlite_header(tmp_path): + """A real SQLite database at ``/sqlite_exact.sqlite3`` registers + as sqlite_exact. Mirrors the chroma analog at + ``test_chroma_detect_matches_palace_with_sqlite_header``. + """ + make_minimal_sqlite_exact_sqlite(tmp_path) + assert SQLiteExactBackend.detect(str(tmp_path)) is True + assert SQLiteExactBackend.detect(str(tmp_path.parent)) is False + + +def test_sqlite_exact_detect_rejects_empty_sqlite_exact_sqlite(tmp_path): + """A 0-byte ``sqlite_exact.sqlite3`` is not a sqlite_exact palace (#1893). + + Same root cause as the chroma side: bare ``sqlite3.connect()`` against + a missing path leaves a 0-byte file behind because the SQLite header is + written on the first statement, not on connect. Detection must reject + that artifact so it cannot trip ``BackendMismatchError`` against a real + non-sqlite_exact backend marker in the same directory. + """ + (tmp_path / "sqlite_exact.sqlite3").write_bytes(b"") + assert SQLiteExactBackend.detect(str(tmp_path)) is False + + +def test_sqlite_exact_detect_rejects_non_sqlite_file(tmp_path): + """A non-SQLite file at the ``sqlite_exact.sqlite3`` path is not + sqlite_exact. Defends against partial writes / garbage content / anything + that lands at the canonical path but isn't actually a SQLite database. + """ + (tmp_path / "sqlite_exact.sqlite3").write_bytes(b"not a sqlite file" * 4) + assert SQLiteExactBackend.detect(str(tmp_path)) is False + + def test_sqlite_exact_exact_ranking_uses_cosine(tmp_path): _backend, col = _collection(tmp_path) halfway = [0.5, math.sqrt(0.75)] diff --git a/tests/test_sync.py b/tests/test_sync.py index 148bdc6..50fba19 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -11,6 +11,8 @@ from pathlib import Path import chromadb import pytest +from _chroma_palace_helper import make_minimal_chroma_sqlite + def _seed_drawers(palace_path, repo_path, deleted_path, elsewhere_path): """Populate the drawers collection with 6 entries covering all buckets.""" @@ -1446,7 +1448,7 @@ class TestServiceRunSyncReport: os.makedirs(palace) # Satisfy run_sync's detect_backend_for_path guard without spinning up # the real Chroma/embedder stack (which would disturb sys.stdout). - Path(palace, "chroma.sqlite3").touch() + make_minimal_chroma_sqlite(palace) monkeypatch.setattr( sync_module, "sync_palace", @@ -1472,7 +1474,7 @@ class TestServiceRunSyncReport: palace = os.path.join(tmp_dir, "palace") os.makedirs(palace) - Path(palace, "chroma.sqlite3").touch() + make_minimal_chroma_sqlite(palace) monkeypatch.setattr( sync_module, "sync_palace",