Skip to content

Commit 4260706

Browse files
committed
fix(backends/chroma): release SQLite file lock on close_palace/close (#1067)
ChromaBackend.close_palace() and close() evicted cached PersistentClients from self._clients without calling client.close(), so chromadb 1.5.x kept the rust-side SQLite file lock until GC. Reopening the same palace path after shutil.rmtree + re-create within one process then failed with SQLITE_READONLY_DBMOVED (SQLite code 1032). Add _close_client() helper with a try/except fallback for older chromadb, and route close_palace(), close(), and the DB-file-missing invalidation branch of _client() through it. The mtime/inode auto-invalidation branch is left as-is: callers there may still hold a live ChromaCollection handle, and closing out from under them clears the rust bindings mid-use. Regression tests cover close_palace reopen-same-path and whole-backend close for multiple palaces.
1 parent 6890948 commit 4260706

2 files changed

Lines changed: 72 additions & 3 deletions

File tree

mempalace/backends/chroma.py

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,20 @@ def _as_list(v: Any) -> list:
205205
return [v]
206206

207207

208+
def _close_client(client) -> None:
209+
"""Call ``PersistentClient.close()`` if available, swallow otherwise.
210+
211+
chromadb 1.5.x exposes ``Client.close()`` to release rust-side SQLite
212+
file locks; older versions relied on GC. Try/except keeps forward-compat.
213+
"""
214+
if client is None:
215+
return
216+
try:
217+
client.close()
218+
except Exception:
219+
logger.debug("client.close() unavailable or failed", exc_info=True)
220+
221+
208222
class ChromaCollection(BaseCollection):
209223
"""Thin adapter translating ChromaDB dict returns into typed results."""
210224

@@ -506,7 +520,7 @@ def _client(self, palace_path: str):
506520
db_path = os.path.join(palace_path, "chroma.sqlite3")
507521
# DB was present when cache was built but is now missing → invalidate.
508522
if cached is not None and not os.path.isfile(db_path):
509-
self._clients.pop(palace_path, None)
523+
_close_client(self._clients.pop(palace_path, None))
510524
self._freshness.pop(palace_path, None)
511525
cached = None
512526
cached_inode, cached_mtime = 0, 0.0
@@ -605,14 +619,22 @@ def get_collection(
605619
return ChromaCollection(collection)
606620

607621
def close_palace(self, palace) -> None:
608-
"""Drop cached handles for ``palace``. Accepts ``PalaceRef`` or legacy path str."""
622+
"""Drop cached handles for ``palace`` and release its SQLite file lock.
623+
624+
Accepts ``PalaceRef`` or legacy path str. chromadb's rust-side file
625+
lock is held until ``PersistentClient.close()`` is called, so plain
626+
dict eviction would leave the palace path unreopenable and
627+
unremovable in the same process.
628+
"""
609629
path = palace.local_path if isinstance(palace, PalaceRef) else palace
610630
if path is None:
611631
return
612-
self._clients.pop(path, None)
632+
_close_client(self._clients.pop(path, None))
613633
self._freshness.pop(path, None)
614634

615635
def close(self) -> None:
636+
for client in self._clients.values():
637+
_close_client(client)
616638
self._clients.clear()
617639
self._freshness.clear()
618640
self._closed = True

tests/test_backends.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
import shutil
23
import sqlite3
34

45
import chromadb
@@ -205,6 +206,52 @@ def test_query_empty_preserves_embeddings_outer_shape_when_requested():
205206
assert not_requested.embeddings is None
206207

207208

209+
def test_chroma_close_palace_releases_sqlite_lock_for_reopen(tmp_path):
210+
"""close_palace must release chromadb's rust-side SQLite file lock so
211+
a fresh PersistentClient on the same path after shutil.rmtree can
212+
write without hitting SQLITE_READONLY_DBMOVED."""
213+
backend = ChromaBackend()
214+
palace_path = tmp_path / "palace-a"
215+
ref = PalaceRef(id=str(palace_path), local_path=str(palace_path))
216+
217+
col = backend.get_collection(palace=ref, collection_name="mempalace_drawers", create=True)
218+
col.upsert(documents=["hello"], ids=["a"], metadatas=[{"k": "v"}])
219+
220+
backend.close_palace(ref)
221+
shutil.rmtree(palace_path)
222+
223+
col = backend.get_collection(palace=ref, collection_name="mempalace_drawers", create=True)
224+
col.upsert(documents=["world"], ids=["b"], metadatas=[{"k": "v2"}])
225+
assert col.count() == 1
226+
227+
228+
def test_chroma_close_releases_all_cached_clients(tmp_path):
229+
"""close() must release every cached client's SQLite file lock so any
230+
of their palace paths can be reopened by a fresh backend in the same
231+
process."""
232+
backend = ChromaBackend()
233+
palace_a = tmp_path / "palace-a"
234+
palace_b = tmp_path / "palace-b"
235+
ref_a = PalaceRef(id=str(palace_a), local_path=str(palace_a))
236+
ref_b = PalaceRef(id=str(palace_b), local_path=str(palace_b))
237+
238+
for ref in (ref_a, ref_b):
239+
backend.get_collection(palace=ref, collection_name="mempalace_drawers", create=True).upsert(
240+
documents=["x"], ids=["x"], metadatas=[{"k": "v"}]
241+
)
242+
243+
backend.close()
244+
245+
for path in (palace_a, palace_b):
246+
shutil.rmtree(path)
247+
ref = PalaceRef(id=str(path), local_path=str(path))
248+
fresh = ChromaBackend()
249+
col = fresh.get_collection(palace=ref, collection_name="mempalace_drawers", create=True)
250+
col.upsert(documents=["y"], ids=["y"], metadatas=[{"k": "v2"}])
251+
assert col.count() == 1
252+
fresh.close()
253+
254+
208255
def test_chroma_cache_invalidates_when_db_file_missing(tmp_path):
209256
"""A palace rebuild that removes chroma.sqlite3 must drop the stale cache.
210257

0 commit comments

Comments
 (0)