diff --git a/client/cli/chat_settings.py b/client/cli/chat_settings.py index b5a55ea..f10b2df 100644 --- a/client/cli/chat_settings.py +++ b/client/cli/chat_settings.py @@ -148,6 +148,17 @@ def resource_dir(env_var, name): STATE_DIR = os.environ.get("SPEAR_STATE_DIR") or _TEST_STATE or APP_DIR os.makedirs(STATE_DIR, exist_ok=True) +# An image ships its index and names it here. What a session indexes then goes +# beside its other state, where it outlives the container, and is read before +# the shipped one. The indexers are separate programs and learn the place from +# the environment. + +SHIPPED_DB_PATH = os.environ.get("SPEAR_SHIPPED_DB_PATH") or "" + +if SHIPPED_DB_PATH and not os.environ.get("SPEAR_DB_PATH") and not _TEST_STATE: + DB_PATH = f"{STATE_DIR}/chromadb" + os.environ["SPEAR_DB_PATH"] = DB_PATH + # All of these accumulate, so all of them live under STATE_DIR: the audit # trail, the runtime trace, the tool results a later turn may re-read, the # session records and the file checkpoints an undo restores from. Rooting them diff --git a/client/cli/corpus_search.py b/client/cli/corpus_search.py index 788e09b..037ab03 100644 --- a/client/cli/corpus_search.py +++ b/client/cli/corpus_search.py @@ -7,7 +7,7 @@ import subprocess from retrieval import embedding from cli import session_workspace -from cli.chat_settings import APP_DIR, DB_PATH +from cli.chat_settings import APP_DIR, DB_PATH, SHIPPED_DB_PATH from cli.corpus_registry import corpora_below, load_projects from cli.terminal_ui import C_DIM, C_RST, C_WARN @@ -603,7 +603,40 @@ def _db(): """ import chromadb - return chromadb.PersistentClient(path=DB_PATH) + own = chromadb.PersistentClient(path=DB_PATH) + + if (SHIPPED_DB_PATH and os.path.isdir(SHIPPED_DB_PATH) + and os.path.realpath(SHIPPED_DB_PATH) != os.path.realpath(DB_PATH)): + return LayeredIndex(own, chromadb.PersistentClient(path=SHIPPED_DB_PATH)) + + return own + + +class LayeredIndex: + """The user's index over the one an image ships. + + A collection is looked up in the user's first, so a corpus indexed again + by the user answers from that; everything that writes goes to the user's. + """ + + def __init__(self, own, shipped): + self._own, self._shipped = own, shipped + + def get_collection(self, name, **kwargs): + try: + return self._own.get_collection(name, **kwargs) + except Exception: + return self._shipped.get_collection(name, **kwargs) + + def list_collections(self): + mine = list(self._own.list_collections()) + names = {collection.name for collection in mine} + + return mine + [collection for collection in self._shipped.list_collections() + if collection.name not in names] + + def __getattr__(self, name): + return getattr(self._own, name) def archive_index(rec): diff --git a/client/tests/test_layered_index.py b/client/tests/test_layered_index.py new file mode 100644 index 0000000..f171209 --- /dev/null +++ b/client/tests/test_layered_index.py @@ -0,0 +1,55 @@ +"""The user's index is read before the one an image ships, and is the one +written.""" + +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import chromadb + +from cli import corpus_search + + +def vectors(count): + return [[float(i), 1.0] for i in range(count)] + + +class LayeredIndex(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.own = chromadb.PersistentClient(path=f"{self.tmp.name}/own") + self.shipped = chromadb.PersistentClient(path=f"{self.tmp.name}/shipped") + self.index = corpus_search.LayeredIndex(self.own, self.shipped) + + baked = self.shipped.create_collection("baked") + baked.add(ids=["a", "b"], documents=["one", "two"], embeddings=vectors(2)) + + def test_a_shipped_collection_is_found(self): + self.assertEqual(self.index.get_collection(name="baked").count(), 2) + + def test_the_user_s_collection_of_the_same_name_wins(self): + mine = self.own.create_collection("baked") + mine.add(ids=["a"], documents=["mine"], embeddings=vectors(1)) + + self.assertEqual(self.index.get_collection(name="baked").count(), 1) + self.assertEqual([c.name for c in self.index.list_collections()], ["baked"]) + + def test_what_is_created_goes_to_the_user_s(self): + self.index.get_or_create_collection("new") + + self.assertEqual([c.name for c in self.own.list_collections()], ["new"]) + self.assertEqual([c.name for c in self.shipped.list_collections()], ["baked"]) + self.assertEqual(sorted(c.name for c in self.index.list_collections()), + ["baked", "new"]) + + def test_an_unknown_collection_still_fails(self): + with self.assertRaises(Exception): + self.index.get_collection(name="absent") + + +if __name__ == "__main__": + unittest.main() diff --git a/docker/Dockerfile.harness b/docker/Dockerfile.harness index 02f9c2d..c9dea96 100644 --- a/docker/Dockerfile.harness +++ b/docker/Dockerfile.harness @@ -110,6 +110,7 @@ RUN chmod +x /opt/spear/entrypoint.sh /opt/spear/spear-run.sh /usr/local/bin/spe ENV SPEAR_COMMON_STATE_DIR=/opt/spear/common ENV SPEAR_STANDARDS_ROOT=/opt/spear/common/standards ENV SPEAR_STATE_DIR=/opt/spear/state +ENV SPEAR_SHIPPED_DB_PATH=$APP/chromadb ENV SPEAR_CORPUS_ROOT=/corpora ENV PATH=$APP/bin:$PATH WORKDIR /corpora diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 69122b7..8f3f187 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -69,8 +69,7 @@ print(f"corpora: {found} present, {miss} missing " # is the entire reason the tool exists. import textwrap -import chromadb -have = {c.name for c in chromadb.PersistentClient(path=chat_settings.DB_PATH).list_collections()} +have = {c.name for c in corpus_search._db().list_collections()} absent = sorted(n for n, spec in corpus_registry.load_projects().items() if os.path.isdir(spec["path"]) and corpus_search.collection_name_for(spec) not in have)