Skip to content

Commit 195eed2

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 9b35d9f commit 195eed2

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
@@ -177,6 +177,20 @@ def _as_list(v: Any) -> list:
177177
return [v]
178178

179179

180+
def _close_client(client) -> None:
181+
"""Call ``PersistentClient.close()`` if available, swallow otherwise.
182+
183+
chromadb 1.5.x exposes ``Client.close()`` to release rust-side SQLite
184+
file locks; older versions relied on GC. Try/except keeps forward-compat.
185+
"""
186+
if client is None:
187+
return
188+
try:
189+
client.close()
190+
except Exception:
191+
logger.debug("client.close() unavailable or failed", exc_info=True)
192+
193+
180194
class ChromaCollection(BaseCollection):
181195
"""Thin adapter translating ChromaDB dict returns into typed results."""
182196

@@ -449,7 +463,7 @@ def _client(self, palace_path: str):
449463
db_path = os.path.join(palace_path, "chroma.sqlite3")
450464
# DB was present when cache was built but is now missing → invalidate.
451465
if cached is not None and not os.path.isfile(db_path):
452-
self._clients.pop(palace_path, None)
466+
_close_client(self._clients.pop(palace_path, None))
453467
self._freshness.pop(palace_path, None)
454468
cached = None
455469
cached_inode, cached_mtime = 0, 0.0
@@ -542,14 +556,22 @@ def get_collection(
542556
return ChromaCollection(collection)
543557

544558
def close_palace(self, palace) -> None:
545-
"""Drop cached handles for ``palace``. Accepts ``PalaceRef`` or legacy path str."""
559+
"""Drop cached handles for ``palace`` and release its SQLite file lock.
560+
561+
Accepts ``PalaceRef`` or legacy path str. chromadb's rust-side file
562+
lock is held until ``PersistentClient.close()`` is called, so plain
563+
dict eviction would leave the palace path unreopenable and
564+
unremovable in the same process.
565+
"""
546566
path = palace.local_path if isinstance(palace, PalaceRef) else palace
547567
if path is None:
548568
return
549-
self._clients.pop(path, None)
569+
_close_client(self._clients.pop(path, None))
550570
self._freshness.pop(path, None)
551571

552572
def close(self) -> None:
573+
for client in self._clients.values():
574+
_close_client(client)
553575
self._clients.clear()
554576
self._freshness.clear()
555577
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
@@ -204,6 +205,52 @@ def test_query_empty_preserves_embeddings_outer_shape_when_requested():
204205
assert not_requested.embeddings is None
205206

206207

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

0 commit comments

Comments
 (0)